A Basic REST API

Andy Balaam
artificialworlds.net/blog

Contents

The Plan

Using the API

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

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

Using the API

Get a poem (GET):
$ curl http://localhost:8080\
    /api/v1/poems/a-question

{"text": "A voice said, Look me in the stars\nAnd tell me truly, men of earth,\nIf all the soul-and-body scars\nWere not too much to pay for birth.\n", "title": "A Question", "id": "a-question", "author": "Robert Frost"}

Using the API

Add a poem (POST):
$ curl \
    --data '{"title":"Foo", ...' \
    http://localhost:8080\
    /api/v1/poems

foo

Returns the ID

Using the API

Replace a poem (PUT):
$ curl --request PUT \
    --data '{"title":"Foo", ...' \
    http://localhost:8080\
    /api/v1/poems/foo

Using the API

Delete a poem (DELETE):
$ curl --request DELETE \
    http://localhost:8080\
    /api/v1/poems/foo

Using the API

Amend a poem (PATCH):
$ curl --request PATCH \
    --data '{"text":"Cheer up"}' \
    http://localhost:8080\
    /api/v1/poems/a-question

Layers

web.py app

urls = (
    "/api/v1/poems(.*)",
        "poemtube.api.v1.Poems",
    "/",
        "poemtube.site.Home",
)

HTTP

# poems.py
from poemtube.jsonapi \
    import json_poems

class Poems:
    def GET( self, urlid ):
        web.header( 'Content-Type',
            'application/json' )

        return json_poems.GET(
            self.db, clean(urlid) )

JSON

# json_poems.py
import json
from poemtube import \
    listpoems, getpoem

def GET( db, id ):
    if id == "":
        return json.dumps(
            listpoems( db ) )
    else:
        return json.dumps(
            getpoem( db, id ) )

JSON

# json_poems.py
import json

def POST( db, data ):
    d = json.loads( data )
    return json.dumps(
        addpoem( db, d["title"],
        d["author"], d["text"] ) )

Functionality

# listpoems.py

def listpoems( db ):
    return ( id for id in db.poems )

Functionality

# getpoem.py
from copy import copy

def getpoem( db, id ):
    ans = copy( db.poems[id] )
    ans["id"] = id
    return ans

Functionality

# addpoem.py
from make_id import make_id

def addpoem(db,title,author,text):
    id = make_id( db, title )
    db.poems[id] = {
        "title"  : title,
        "author" : author,
        "text"   : text
    }
    return id

More info

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