Django API With a Single Line of Code

By Rich Jones

Hey all!

I've whipped up a neat little project as part of my 'django-easy' series: Django-Easy-API.

It's an incredibly easy method of adding serialization to any page of your Django app. Whereas the wonderful Django-REST-Framework provides everything you need to make a "complete" API for your site, it's fairly complicated and takes a good deal time to set up. Django-Easy-API has very a different philosophy: every page should be serializable, and it should be incredibly easy to set up.

That's why with Django-Easy-API, you can give your whole site an API with only a single line of code!


So, suppose you're running an online shop, if you have a page for an item which displays rendered HTML for a URL like this:

Then with django-easy-api installed, to get a JSON-consumable of the page, you only need to go to:

or, for XML:

The only thing you need to do is change a single import:


# from django.shortcuts import render_to_response
from easy_api.shortcuts import render_to_response


which will add this ability to all of your views, or, to just use it for a single view, use easy_api.shortcuts.render_to_easy_api_response instead of django.shortcuts.render_to_response.

That's it!

And that's all it takes to add a machine-consumable version of your site. It won't give you a "true API" (for that you'll want to look at the wonderful, albeit chunky, Django-REST-Framework), but it'll give you everything you need to have a feed-able version of your site. This is great for feeding into other apps, or integrating with mobile applications, or piping to other services.

For more examples and advanced usage, check out Django-Easy-API on GitHub.


See More Posts About:


Posted by Rich Jones

LinkedIn Website