C# Get all records from Web API where pagination is implemented

Viewed 40

My requirement is accessing a third party Web API, which has total of 120 records (just an example - it can be more). The Api has pagination implemented which returns default 50 records based on page number. By passing {Page} in parameters, we can get other 50 records for that page number:

Example :

https://www.thirdpartapi.com/users?Page=1

https://www.thirdpartapi.com/users?Page=2

This is the response from API -

{
 "total" : 120,
 "users" : [
     {
        "id" : "abc123",
        "firstName" : "First1",
        "lastName" : "Last1"
     },
     {
        "id" : "abc124",
        "firstName" : "First2",
        "lastName" : "Last2"
     },
     ...... 50 users
  ]
}

I want to get all 120 users records from the Web API.

this is my Response model:

public class ApiResponse
{
     public int total { get; set; }
     public List<Users> users { get; set; }
     public ApiResponse()
     {
         users = new List<Users>();
     }
}

public class Users
{
     public string id { get; set; }
     public string firstName { get; set; }
     public string lastName{ get; set; } 
}

I am making a recursive call to the WebAPI to get all the 120 records:

List<Users> = (List<Users>)CallApi();

private List<Users> CallApi(int? pageNumber = 1)
{        
    var response = webmanager.RestApi("https://www.thirdpartapi.com/users?Page={pageNumber}");
    
    ApiResponse data = (ApiResponse)JsonConvert.DeserializeObject(response, typeOf(ApiResponse));

    if(data.users.Count > 0)
    { 
        data.users.AddRange((IEnumberable<Users>)CallApi(pageNumber + 1));
        return data.users;
    }
    else
        return data.users;
 }
 

I am able to get all the Users (120). But is this an optimal way to call an API? Please suggest a better solution.

1 Answers

Since its a third party API, calling the API multiple times is the only option. Just a minor suggestion would be to keep track of the count of records fetched and check if it's greater than the total count. Here you could avoid the 4th API call if you do so.

Related