Q:

Google App Engine query 50 results at a time with a nextPageToken

I have the following Api Method in my GAE Cloud endpoint:
@ApiMethod(name = "getConferences", path = "get_conferences", httpMethod = ApiMethod.HttpMethod.POST)
    public List<Conference> getConferences(@Named("userId") Long userId) {

        List<Conference> conferenceList = ofy().load().type(Conference.class)
                    .ancestor(Key.create(User.class, userId))
                    .order("-createdDate").list();

        return  conferenceList; 

}
It works great and returns for me all the conferences a given user created sorted desc by date. The Conference class has the following property to specify that it has a User parent:
@Parent
private Key<User> userKey;

My question is, how can I change the above method to return only 50 results (conferences) at a time, and also be able to specify a parameter that takes something like a nextPageToken to give me the next 50 results? 
I've seen this done in other API methods but can't seem to find a good example with GAE or Cloud Endpoints that works.

A:

Rather than returning List<Conference> you should return com.google.api.server.spi.response.CollectionResponse<Conference>.
Add a named parameter, such as @Named("nextPageToken") String pageToken.
If pageToken != null, after .order() you need to chain .startAt(Cursor.fromWebSafeString(pageToken))
You also need to add .limit(50), since you want that to be your page size.
Instead of .list() use .iterator(), which has a getStartCursor() method. Use this and the iterator to construct the CollectionResponse.

See also this page for a non-Endpoints example of how to use cursors. The rest should be trivial.

