Paging in a REST API

Andy Balaam
artificialworlds.net/blog

Contents

Recap

Recap

List poems (GET):
$ curl http://localhost:8080\
    /api/v1/poems
    

["this-is-a-photo", "a-question"]

Why paging?

Page numbers

/api/v1/poems?page=3

Page numbers

/api/v1/poems/page/3

Archives

/api/v1/poems_archive/2009/11

HTTP style

Use headers instead of URL:
$ curl -i \
    --header "Range: page=3" \
    http://localhost:8080/api/v1/poems

HTTP style

Response:
HTTP/1.1 206 Partial Content
Content-Type: application/json
Transfer-Encoding: chunked
Content-Range: page=3
Date: Fri, 15 Nov 2013 09:50:51 GMT
Server: localhost

HTTP style

The Twitter Way

/api/v1/poems?since_id=foo&count=20

The Twitter Way

def listpoems( db, count, since_id ):
    ids = ( id for id in db.poems )

    # Skip up to since_id
    ids = itertools.dropwhile(
        lambda id: id != since_id, ids )

    # Skip 1 more
    ids = itertools.islice(
        ids, 1, None )

The Twitter Way

def listpoems( db, count, since_id ):
    # ...

    # Stop when we reach count items
    ids = itertools.islice(
        ids, 0, count )

    return ids

The Twitter Way

# poems.py
def GET( self, urlid ):
    # ...
    return json_poems.GET(
        self.db, clean(urlid),
        web.input()
    )

TODO: Hyperlinked

<link
    rel="next"
    href="...feed.atom?page=2"
/>

More info

Videos youtube.com/user/ajbalaam
Twitter @andybalaam
Blog artificialworlds.net/blog
Projects artificialworlds.net