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(

Azure AD and AWS Cognito side-by-side

In the last few weeks, I was involved in multiple opportunities on Microsoft Azure and Amazon, where we had to analyse AWS Cognito, Azure AD and other solutions that are available on the market. I decided to consolidate in one post all features and differences that I identified for both of them that we should need to take into account. Take into account that Azure AD is an identity and access management services well integrated with Microsoft stack. In comparison, AWS Cognito is just a user sign-up, sign-in and access control and nothing more. The focus is not on the main features, is more on small things that can make a difference when you want to decide where we want to store and manage our users.  This information might be useful in the future when we need to decide where we want to keep and manage our users.  Feature Azure AD (B2C, B2C) AWS Cognito Access token lifetime Default 1h – the value is configurable 1h – cannot be modified

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine: threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration: TeamCity .NET 4.51 EF 6.0.2 VS2013 It see