Djangocon: What it’s really like building RESTful APIs with Django - Paul Hallett

Tags: django, djangocon

(One of the summaries of a talk at the 2015 Djangocon EU conference).

Paul Hallett considers himself an “API fanatic”. He works for lyst, a website for buying clothes. They had an existing API, json-rpc, and wanted to have a better API that fitted better with http.

RPC (remote procedure call) means you only have one endpoint (=url) and everything is a POST request, even if you only request information.

“RPC for http is bad” is what he said. He wanted to do it with django rest framework. Django is a batteries-included webframework, django rest framework is a batteries-included API framework.

If you need to re-build some existing API as a rest API, think of it as a chance to rebuild. If it is an existing API, the program probably changed a bit from how it looked originally. Shouldn’t you clean it up a bit? Change a couple of models? The alternatively is to shoe-horn non-fitting models into an otherwise nice API…

REST focuses on Resources. In django terms, you often think “a model”. This isn’t necessarily true, it might be either more or less. A model might actually have two separate sets of attributes that you’d rather treat as two separate resources.

The core rest framework technology you need to use for this is serializers. Basically translators between django models and resources.

Permissions tip: set DEFAULT_PERMISSION_CLASSES to the admin-only one. That way, if you make a mistake, only the admin can access it. Otherwise you might leave too many API endpoints open.

Authentication: always have it. Always do something. Even if it is on the same server. Tokens, a simple string, whatever. But the best option is oauth2. Install the oauthtoolkit to set it up.

Don’t be afraid to bend the rules for http a little bit. If you can make a nice API with just a little bit of rule-bending: that’s fine.

Documentation is necessary. If you don’t have documentation, you have a bad API. You might have a great API and clear endpoints, but documentation is still key. At the bare minimum provide documentation on how to obtain an oauth2 token!

Holiday picture from the Eifel region
 
vanrees.org logo

About me

My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I'm happily married to Annie van Rees-Kooiman.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):