Building a JSON API
This page builds a small JSON API. It uses nothing that the other pages have not covered; it shows how routing, hooks, and error handlers fit together so that each handler stays a few lines long.
The layout
my_webapps
|-- webapp1.page.get.py
|-- /webapp1
|-- API.404.py
|-- API.405.py
|-- API.hook.late.py
|-- /API
|-- users.page.get.py
|-- users.page.post.py
|-- /users
|-- {user_id}.page.get.py
Everything that makes this an API sits in three files beside the API directory. The handlers inside it
only deal with users.
JSON on every response
A late hook sets the content type for the whole API, so no handler has to:
API.hook.late.py:
def main(response):
response.content_type = "application/json"
return response
Late hooks also run on error responses, so errors are labeled as JSON too.
Reading and listing
users.page.get.py handles GET /API/users:
import json
def main(users):
return json.dumps(list(users.values()))
{user_id}.page.get.py handles GET /API/users/<id>. Its name is a
placeholder: it stands for any one path segment, and the segment is passed in as
user_id.
import json
def main(user_id, abort, users):
if user_id not in users:
abort(404)
return json.dumps(users[user_id])
Each handler returns a string, which Cylinder
uses as the response body. users is an
extra parameter; here it is a dictionary standing in for a
database.
Neither handler checks the shape of the URL. Nobody wrote a file for /API/users/1/extra, so it is a 404
before any of this code runs.
Creating
users.page.post.py handles POST /API/users:
import json
def main(request, response, abort, users):
body = request.get_json(silent=True)
if not isinstance(body, dict) or "name" not in body:
abort(400, "A JSON object with a name is required")
user_id = str(len(users) + 1)
users[user_id] = {"id": user_id, "name": body["name"]}
response.status_code = 201
response.headers["Location"] = f"/API/users/{user_id}"
return json.dumps(users[user_id])
request.get_json() is Werkzeug’s. With silent=True it returns None for a body that is not valid JSON,
which the handler turns into a 400.
This handler serves POST /API/users and nothing beneath it. A POST to /API/users/1 is not its
business, and the next section says what answers it.
Refusing other methods
There is nothing to write for this. A request with a method that its URL has no file for gets a 405, and
the Allow header of that response lists the methods the URL does have a file for:
Request |
Response |
|---|---|
|
|
|
|
|
|
The list is read from the filenames, so it cannot fall out of step with them: adding users.page.put.py
adds PUT to the header. See When nothing matches.
Errors as JSON
An error handler beside the API directory covers everything under /API. This one gives every 404 the
same shape:
API.404.py:
import json
def main(e):
return json.dumps({"error": e.name, "detail": e.description, "status": e.code})
There is one error handler file per status code, and all of them can share one function. Put the function in a normal module:
# api_errors.py
import json
def as_json(e):
return json.dumps({"error": e.name, "detail": e.description, "status": e.code})
and each error handler becomes two lines:
API.405.py:
from api_errors import as_json
def main(e):
return as_json(e)
Add API.400.py and API.500.py the same way. The site outside /API is unaffected and keeps its HTML
error pages.
Nested resources
A placeholder can be a directory, so one resource can sit beneath another. These files serve one post of a
user at /API/users/<id>/posts/<id>:
|-- /users
|-- {user_id}.hook.early.py
|-- /{user_id}
|-- /posts
|-- {post_id}.page.get.py
{post_id}.page.get.py receives both values:
import json
def main(user_id, post_id, abort, posts):
post = posts.get(post_id)
if post is None or post["user"] != user_id:
abort(404)
return json.dumps(post)
posts is another extra parameter, passed in beside users.
A check that belongs to the parent goes in a hook named for it. {user_id}.hook.early.py runs for
/API/users/<id> and for every path beneath it, so no handler there has to ask whether the user exists:
def main(response, user_id, abort, users):
if user_id not in users:
abort(404)
return response
A parent in the URL is not a permission check. Whether a visitor may see a post is decided from the post and the visitor, in the same way that the handler compares the post’s user with the one in the URL.
Nesting is a choice. A flat URL such as /API/posts/456 identifies the same post from one value, and
/API/posts?user=1&tag=python combines filters where a nested URL can name only one parent. Nest a
resource that only makes sense inside its parent, and give one that stands by itself a path of its own.
Wiring it up
cylinder_main.py supplies the users store:
import cylinder
import waitress
users = {}
def main():
app = cylinder.get_app(app_map)
waitress.serve(app, host="127.0.0.1", port=8080)
def app_map(request):
return "my_webapps", "webapp1", {"users": users}
if __name__ == "__main__":
main()
A dictionary shared between requests is fine for a demonstration. A real API would pass a database session factory here, and anything shared between threads needs the care described under thread safety.
Trying it
curl -i -X POST -H "Content-Type: application/json" -d '{"name": "Ada"}' http://127.0.0.1:8080/API/users
curl -i http://127.0.0.1:8080/API/users
curl -i http://127.0.0.1:8080/API/users/1
curl -i http://127.0.0.1:8080/API/users/99
curl -i -X DELETE http://127.0.0.1:8080/API/users/1
The fourth request returns a 404 with a JSON body, and the fifth a 405 with an Allow header.
What to notice
Each handler does one thing and is short enough to read at a glance.
Cross-cutting behavior is in the tree, where you can see what it covers: one hook for the content type, one error handler per status.
The shape of every URL is in the tree too. No handler takes a path apart. A URL that has no file is a
404and a method that has no file is a405, both without any code.Adding
/API/ordersmeans addingorders.page.get.py. The content type and error format already apply to it.Protecting the API takes one more file, an early hook named
API.hook.early.py.