Nathan Borror

# Creating a basic API with Django Creating a simple public API for your site is a lot easier than you may think with Django. You're basically just creating another view and serving it as XML or JSON instead of HTML. ## Step 1) What's public? Decide what you want to be public. The best answer is the stuff you're already displaying in your HTML templates. Then you need to create an entry in your url conf. ```python url(r'^api/v1/(?P[-\w]+)/notes/?$', 'readernaut.api.views.user_notes'), ``` ## Step 2) Create the view In the case for [Readernaut](http://readernaut.com) I wanted to provide an XML feed for users notes. Here is what the view looks like: ```python def user_notes(request, username): reader = get_object_or_404(User, username__iexact=username) note_list = Note.objects.filter(user=reader) context = { 'reader': reader, 'note_list': note_list } return render_to_response('api/note_list.html', context, context_instance=RequestContext(request), mimetype='application/xml') ``` This is a simplified version of the view but, as you can see, you could easily add pagination and other hooks to handle ordering and such. ## Step 3) Create the template The view is pointing to the template api/note_list.html so all we need to do is create that file and build out our XML schema. ```xml {% for note in note_list %} {{ note.id }} {{ note.user }} {{ note.book_edition }} {{ note.book_edition.isbn }}

Nathan Borror

{{ note.page_reference }} {{ note.created|date:"Y-m-d G:i T" }} {{ note.modified|date:"Y-m-d G:i T" }}
{% endfor %}
``` How you define your XML templates is up to you. I name my templates with the .html extention simply because my text editor highlights the syntax better than if it were XML. It doesn't matter because the mimetype dictates how the file is served up. Good luck!