Paging a resource collection

It is not considered good practice to return all resources that you may have in the database (or in any other data source) to a client in response to a GET API call. A very common approach for limiting the resource collection returned by an API is to allow the client to specify the offset and the page size for the collection. For example, the API that allows the client to specify the offset and the limit for the resource collection as the query parameters is /departments?offset=1&limit=20.

The following code snippet demonstrates how you can build a JAX-RS resource method that takes the offset and the page size (limit) sent by the client via query parameters:

@GET 
@Produces("application/json") 
public List<Department> findDepartments(@QueryParam("offset")  
@DefaultValue("0") Integer offset, @QueryParam("limit") 
@DefaultValue("20") Integer limit) { //Complete method implementation is not shown for brevity return findDepartmentEntitiesInRange(offset, limit); }

The preceding example is the simplest solution for paging a resource collection. You can improve this solution by including additional attributes in the collection resource representation as follows:

  • hasMore: This attribute indicates whether the collection has more elements to be retrieved
  • limit: This attribute indicates the limit used by the server while querying the collection; this scenario arises if the limit is missing in the client request
  • count: This attribute indicates the total number of elements in the collection
  • totalSize: This attribute indicates the number of elements on the server that match the criteria used for reading the collection
  • links: This attribute contains links to the next and the previous sets

The following example illustrates the resource collection returned by the server with the additional pagination attribute that we discussed:

{ 
    "departments": [{ 
        "departmentId": "11", 
        "departmentName": "HR" 
    },{ 
        "departmentId": "12", 
        "departmentName": "IT" 
    },...  
    ], 
    "hasMore": true, 
    "count": 10, 
    "totalSize": 25, 
    "links": [ 
        {"rel":"self", 
        "href":"/hrapp/api/departments?offset=10&limit=10"}, 
        {"rel":"prev", 
        "href":"/hrapp/api/departments?offset=0&limit=10"}, 
        {"rel":"next", 
        "href":"/hrapp/api/departments?offset=20&limit=10"} 
    ] 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.9.169