How to Create a REST API in Django
How to Create a REST API in Django
A discussion of REST and how to implement this important programming concept into your Django application when working with API integration.
Join the DZone community and get the full member experience.Join For Free
SnapLogic is the leading self-service enterprise-grade integration platform. Download the 2018 GartnerMagic Quadrant for Enterprise iPaaS or play around on the platform, risk free, for 30 days.
REST is an acronym that starts for REpresentational State Transfer. It's a dynamic system based around giving the user what he or she needs at any particular point in time, allowing a system to take in a wide range of data and generate outputs based on what is required. Building a REST API in Django isn't as hard as it seems, especially since Django is already a web-based framework. Getting from framework to API isn't complicated, but there's a lot of places where one can trip up. This overview assumes that you've already installed Django and understand how to create a new project as well as have a basic working knowledge of Django.
Hierarchy and Django for REST
In Django, there are different levels of interface. At the top is the Django project. From the project, you can then create a new app which will use your REST API. This API is best used in a project that has a lot of calls to and from the backend. After creating the app, the next step would be to create a couple of models for use with our REST API app. You can use the standard models or use models that you code yourself, whichever one is more viable for your app. If you have a lot of custom classes, then coding the models yourself might be a more valid approach. Your models would take the shape of typical classes like:
class SomeClass(models.Model): name = models.CharField() description = models.TextField() some_text_variable = models.TextField() slug = models.SlugField() etc.
Define your relationships between your Django models using
ForeignKey and include the respective
on_delete behavior. From there, you set up your rendering models, allowing you to make sense of the data that will be coming in from your queries.
Building a REST API
In its native form, Django doesn't use REST APIs, but they can be added via the Django Rest Framework. To include the Django Rest Framework in your project simply run the following command:
pip install djangorestframework
Following this, you need to open the settings.py file for your project and include the line '
rest_framework' at the bottom of it. Doing so allows your project to now utilize the REST framework as designed for Django.
Now that we can use REST, how do we tap into its amazing power? Well, REST depends on sending and receiving data in JSON format, so, to use REST successfully, we'd need to convert our models to be usable with JSON and that means we need to drop in some serializers.
We can quickly and easily define serializers for our models by deriving our classes from ModelSerializer. Doing so allows our classes to be serializable so that we can send and receive JSON data structures from them. JSON, in general, is easy to parse and can quickly be formatted to fit our needs as well as create great user interface pages for use by the end user. But in order for us to have great pages, we need to first build viewsets for our data.
The standard views that come with Django have a lot of overhead code that makes bending them to your will a bit inconvenient. That's why viewsets were designed for use with Django. A viewset doesn't require you to know all the boilerplate code that you have to use with the standard views, it just gives you a way to output your data in a form and fashion that you desire. It covers all the code required to interact via POST, PATCH, PUT, GET and DELETE. The basic structure of the viewsets looks like this:
from rest_framework import viewsets from . import serializers from . import models class SomeClass(viewsets.ModelViewSet): serializer_class = serializers.SomeClassSerializer queryset = models.SomeClass.objects.all()
queryset above is a bit odd. Despite it being called on all the objects in my class, we won't actually utilize
queryset until we send it a query. Then it steps through every single element in our generic class and pulls out the relevant ones, just like if we were using a database.
serializer_class ensures that our ingoing and outgoing data is handled properly.
Wiring Up Our URLs
The final thing we need to do to finish our foray into REST is to wire up our output to URLs. The Django Rest Framework handles viewsets using routers. A router, according to this Django tutorial, can be defined in the urls.py file with the following code snippet:
from rest_framework import routers from . import views router = routers.DefaultRouter() router.register('SomeClass', views.SomeClassViewSet) urlpatterns = [ path('', include(router.urls)) ]
We initially create a default router and then register our class to the viewset we intend to use with it. From there, you can simply include your URL in
urlspatterns to bring it into the app and use it as you see fit.
And that's about it! At the end of this, you should have a general grasp of how to use REST APIs in Django in a generic way. The best way to learn code and coding, however, is to experiment with it yourself. Setting yourself a task that requires accessing different data types in order for it to be displayed to a user is a great way to challenge yourself. With some basic knowledge of REST APIs, you can now look at more specific examples to get a better idea of how they're used.
Opinions expressed by DZone contributors are their own.