Categories: archive |code

Simple JSON API in Django

For the Bible API, I made the decision early on that I was going to be using JSON for the API.

Creating a JSON API in Django is extremely simple.

views.py

from django.core import serializers
from django.http import HttpResponse

def verses(request, version, book, chapter, verse, verse2):
  '''Returns a list of verses for a given version, book, chapter, and optional verses'''
  verses = Verse().get_verses(version, book, chapter, verse, verse2)
  if 'application/json' in request.META.get('HTTP_ACCEPT'):
    return HttpResponse(serializers.serialize("json", verses), mimetype='application/json')
  else:
    #do some non-json stuff here
    return...

First, we make sure to import serializers from django.core.

In the verses method, we get the verses from the model. Next, we check if the HTTP_ACCEPT header contains application/json. If so, then we return an HttpResponsewith the verses serialized to “json” with a mimetype of application/json.

You can then test your API using curl.

curl --header "Accept: application/json" http://url/path/to/your/api/

And that’s it. You can also do the same with XML if you so choose.