Skip to main content

How to define a REST service with pagination support

Part 1: http://vunvulearadu.blogspot.ro/2014/08/how-to-define-rest-service-with.html
Part 2: http://vunvulearadu.blogspot.ro/2014/08/how-to-define-rest-service-with_17.html

In this blog we will talk about REST API and pagination. Almost all services that are now created are exposed in REST format. This format give us the possibility to expose an endpoint that can be consumed by numerous devices and platforms from laptops to tables and phones.
There are different ways to expose a collection of items using pagination. In the next part I will present a mechanism to expose collection of items using pagination in REST.

Request

A new page request in REST format is pretty simple when we talk about pagination. We need to crucial information for such a requests – page number and page size. Because we request content it is obviously that we will use the GET method.
When we send a request using GET, all request information should be in the URL. We can end up with following possibilities:
GET /api/cars?pageNumber=3&pageSize=20
GET /api/cars/20/3
Both version of request can be good. I would say that the first version is better because is clear for clients what each parameter represents. In the second version is not clear what 20 and 3 represents.

Response

The request was the simplest thing. The response is more complicated and there are different opinions about how the response should look like.
It is pretty obvious that a response should contain:

  • List of items
  • Page number
  • Page size

Additional to this we should have:

  • Total items count
  • Total pages count

Of course if we know total items count it is simple to calculate the number of pages, but it is simpler to calculate this number on the server side and send this value to our clients. They will not need to implement the same calculation again and again.
When we expose a REST service, we need to expose all the content that is needed by client to use and navigate in our REST services without having to compute or calculate anything. They should be able to ‘auto discover’ all the features that are available.
Because of this each response should contain URL links that would allow clients to navigate between pages:

  • Next page link
  • Previous page link
  • First page link
  • Last page link

There are people that would say that this is duplicate information, because clients can generate this URL, but a true rest service should expose all the links between resources. It is simpler for clients to navigate between resources in this way. Also we reduce the risk of errors on client’s side.
Response content:
{  
   "pageNumber":1,
   "pageSize":20,
   "totalPages":3,
   "totalItemsCount":46,
   "prevPageLink":"",
   "nextPageLink":"/api/car?page=2&pageSize=20",
   "firstPageLink":"/api/car?page=1&pageSize=20",
   "lastPageLink":"/api/car?page=2&pageSize=20",
   "items":[
                    ...
 ]
}
In the above example we can see that all the information can be found in the content of the response. As we can see, the prevPageLink is empty. The empty string is used when that resource don’t exist. For example when we are on the first page, we cannot have a previous page.
Another possibility is to put all the meta information  related to page in the response heather. In this case the content of the response will have only the array of items. For this we need to create a custom heather where we should add all this information.
Response heather:
{
   "pageNumber":1,
   "pageSize":20,
   "totalPages":3,
   "totalItemsCount":46,
   "prevPageLink":"",
   "nextPageLink":"/api/car?page=2&pageSize=20",
   "firstPageLink":"/api/car?page=1&pageSize=20",
   "lastPageLink":"/api/car?page=2&pageSize=20",
}
Response content:
{
 [
  { item1 }
  { item2 }
                    ...
 ]
}
As we can see second option is cleaner. We have in the response content the list of items without any meta-data related to pagination. This is the solution that I prefer to use.
The downside of this solution is at debug and discovery level, when clients’ needs to access pagination information from heather. To do this they need to write additional code, that can add complexity to the application. Also, if we want to make a request from a browser to see the response, we will not be able to see all the response directly in the browser. We will need a ‘developer’ tool/plugin to access the response heather.
The first solution is extremely clear and easy to use. Even I prefer the second solution, in production we ended up with the first one.

Error codes

The last think that I would like to talk about is error codes. I don’t what to go over each error code that we should return and manage. What we should take into account is the standards HTTP error code. For error that we have in our backend we should use standard HTTP error codes – we should never invent our own error codes or map standard error codes to scenarios where that error codes don’t apply.
Why? Because web developers are used to specifies error codes for different scenarios. We should respect the existing standard, not create a new one.
For example, when the request is invalid (for example the page number is missing) we should return 204 – No Content.
In this blog post we saw different ways how to implement pagination support in our REST services. In the next blog post we will see how we can implement such a service using API Controller and Azure Web Sites.

Part 1: http://vunvulearadu.blogspot.ro/2014/08/how-to-define-rest-service-with.html
Part 2: http://vunvulearadu.blogspot.ro/2014/08/how-to-define-rest-service-with_17.html

Comments

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(...

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills)

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills) The idea that moving to the cloud reduces the costs is a common misconception. The cloud infrastructure provides flexibility, scalability, and better CAPEX, but it does not guarantee lower costs without proper optimisation and management of the cloud services and infrastructure. Idle and unused resources, overprovisioning, oversize databases, and unnecessary data transfer can increase running costs. The regional pricing mode, multi-cloud complexity, and cost variety add extra complexity to the cost function. Cloud adoption without a cost governance strategy can result in unexpected expenses. Improper usage, combined with a pay-as-you-go model, can result in a nightmare for business stakeholders who cannot track and manage the monthly costs. Cloud-native services such as AI services, managed databases, and analytics platforms are powerful, provide out-of-the-shelve capabilities, and increase business agility and innovation. H...