Tuesday, July 16, 2013

REST - Pagination

Pagination is essential when retrieving information from webservices. Sometimes, we have scenarios like mobile applications where a large amount of data can bring problems.  This article aims to show how Facebook API deals with this, and also display an example of query string pagination using JAX-RS (Jersey) and JPA (Hibernate).

The Facebook's platform supports three types of pagination using query string: 

Cursor-based
  • before - This is the cursor that points to the start of the page of data that has been returned.
  • after - This is the cursor that points to the end of the page of data that has been returned.
  • limit - This is the number of individual objects that are returned in each page.

Time-based
  • until - A Unix timestamp or strtotime data value that points to the end of the range of time-based data.
  • since - A Unix timestamp or strtotime data value that points to the start of the range of time-based data.
  • limit - This is the number of individual objects that are returned in each page.

Offset-based
  • offset - This offsets the start of each page by the number specified.
  • limit - This is the number of individual objects that are returned in each page.
Example
This example will stick to the Offset-based pagination, but you can choose the one that fits your requirements.

@GET
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public List<Order> getOrders(
 @QueryParam("offset") Integer offset, 
 @QueryParam("limit") Integer limit){
  
 Query q = _em.createQuery("from Order");
 if(offset != null){
  q.setFirstResult(offset);
 }
 
 if(limit != null){
  q.setMaxResults(limit);
 }
 return (List<Order>) q.getResultList();
}

The URL to access this would be:
/** 
* This URL would return the limit of 20 orders starting from order number 20.
**/
http://www.ivanjunckes.com/resources/orders?offset=20&limit=20

The previous code shows a good path for doing pagination with REST and JAVA. However, there are some other ways of doing pagination, but this is a topic for another article.

See you later!

Source:
https://developers.facebook.com/docs/reference/api/pagination/

3 comments: