Sign inGet started
Responses
What are your thoughts?CancelRespond
There are currently no responses for this story.
Be the first to respond.
You have 2 free member-only stories left this month. Sign up for Medium and get an extra one
Build a REST API with Python Django

S. KhanFollowSep 10, 2020 · 10 min read
Building a REST API in Django is so super easy. In this tutorial, we’ll walk through the steps to get your first API up and running.
Why you need a REST API?
Before we move on to coding, it’s worth considering why you would want to build an API? A REST API is a standardized way to provide data to other applications. Those applications can then use the data however they want.
There are a few key options for a REST API request:
- GET — The most common option, returns some data from the API based on the endpoint you visit and any parameters you provide.
- POST — Creates a new record that gets appended to the database
- PUT — Looks for a record at the given URI you provide. If it exists, update the existing record. If not, create a new record.
- DELETE — Deletes the record at the given URI.
- PATCH — Update individual fields of a record.
Typically, an API is a window into a database. The API back-end handles querying the database and formatting the response. What you receive is a static response, usually in JSON format, of whatever resource you requested.
In simple words, they are window for applications to communicate with one another or even within themselves. To give you an example, in web development, many applications rely on REST APIs to allow the front-end to talk to the back-end. If you’re deploying a React application on top of Django, for instance, you’ll need an API to allow React to consume information from the database.
The process of querying and converting tabular database values into JSON or another format is called serialization.
So let’s get started.
To-do list to create a REST API in Django
Here are the steps to create a REST API:
- Set-up Django
- Create a model in the database that the Django ORM will manage
- Set up the Django REST Framework
- Serialize the model from step 2
- Create the URI endpoints to view the serialized data
1. Set up Django
To create a Django app, we’ll need to install Django. That’s easy enough!
First, though, consider creating a new virtual environment for your project so you can manage your dependencies separately.
1.1 Virtual Environment
Let’s get virtualenvwrapper installed with pip
pip install virtualenvwrapper-win

To create a wrapper folder which will contain the virtual environment and our application
mkdir django-rest
Then create the virtual environment
mkvirtualenv django-rest
Now you should see the environment prefix in your cmd
(django-rest)
Type “workon django-rest” if you do not see the prefix.

1.2 Install Django
Now, we can install Django:
pip install django
Next, let’s start a new Django project by going inside the folder first:
django-admin startproject mysite

If we look at the directory now, we’ll see that Django created a new folder for us. And if we look inside that folder, there’s everything we need to run a Django site. Let’s make sure it works. Test run the Django server by going inside the mysite folder:
python manage.py runserver

Go to localhost:8000 and you should see the Django welcome screen!

1.3 Create API app
We could build our application with the folder structure the way it is right now. However, best practice is to separate your Django project into separate apps when you build something new.
So, let’s create a new app for our API:
python manage.py startapp myapi

1.4 Register the myapi app with the mysite project
We need to tell Django to recognize this new app that we just created. The steps we do later won’t work if Django doesn’t know about myapi.
So, we edit mysite/settings.py
Look for INSTALLED_APPS and add your
INSTALLED_APPS = [
'myapi.apps.MyapiConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

1.5 Migrate the database
Whenever we create or make changes to a model, we need to tell Django to migrate those changes to the database. The Django ORM then writes all the SQL CREATE TABLE
commands for us.
It turns out that Django comes with a few models already built in. We need to migrate those built in models to our database.
(For those of you thinking, “We didn’t create a database!” You’re right. But Django will create a simple SQLite database for us if we don’t specify differently. And SQLite is awesome!)
So, let’s migrate those initial models:
python manage.py migrate

1.6 Create Super User
We’re about to create some models. It would be nice if we had access to Django’s pretty admin interface when we want to review the data in our database.To do so, we’ll need login credentials. So, let’s make ourselves the owners and administrators of this project.
python manage.py createsuperuser
Username (leave blank to use 'shah'):
Email address: admin@insights.school
Password:
Password (again):
Superuser created successfully.
Lets start the SERVER again:
python manage.py runserver
And then navigate to localhost:8000/admin

Log in with your superuser credentials, and you should see the admin dashboard:

2. Create a model in the database that Django ORM will manage
We’ll build it in myapi/models.py
, so open up that file.
Let’s make a database of superheroes! Each hero has a name and an alias that they go by in normal life. We’ll start there with our model:
# models.py
from django.db import modelsclass Hero(models.Model):
name = models.CharField(max_length=60)
alias = models.CharField(max_length=60)
def __str__(self):
return self.name

name
and alias
are character fields where we can store strings. The __str__
method just tells Django what to print when it needs to print out an instance of the Hero
model.
2.2 Make migrations
Remember, whenever we define or change a model, we need to tell Django to migrate those changes.
python manage.py makemigrationspython manage.py migrate

2.3 Register Hero with the admin site
Remember that admin site doesn’t know the Hero
model exists, but with two lines of code, we can tell it about Hero
.
Open myapi/admin.py and make it look like this:
from .models import Hero
admin.site.register(Hero)

Now run the Django server:
python manage.py runserver
And visit localhost:8000/admin

2.4 Create some new heroes
While we’re on the admin site, might as well create a few heroes to play around with in our application.
Click “Add.” Then, make your heroes!

3. Set up Django REST Framework
Time to start thinking about our API. We need to serialize the data from our database via endpoints.
To do that, we’ll need Django REST Framework, so let’s get that installed.
pip install djangorestframework
Now, tell Django that we installed the REST Framework in mysite/settings.py:
INSTALLED_APPS = [
# All your installed apps stay the same
...
'rest_framework',
]

That’s it!
4. Serialize the Hero model
Now we’re starting to get into some new waters. We need to tell REST Framework about our Hero model and how it should serialize the data.
To do so, let’s create a new file — myapi/serializers.py
In this file, we need to:
- Import the Hero model
- Import the REST Framework serializer
- Create a new class that links the Hero with its serializer
# serializers.py
from rest_framework import serializers# import model
from .models import Hero# linking model with serializer
class HeroSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Hero
fields = (‘name’, ‘alias’)

5. Display the data
Now, all that’s left to do is wire up the URLs and views to display the data!
5.1 Views
Let’s start with the view. We need to render the different heroes in JSON format.
To do so, we need to:
- Query the database for all heroes
- Pass that database queryset into the serializer we just created, so that it gets converted into JSON and rendered
In myapi/views.py:
# views.py
from django.shortcuts import render
from rest_framework import viewsets
from .serializers import HeroSerializerfrom .models import Heroclass HeroViewSet(viewsets.ModelViewSet):
queryset = Hero.objects.all().order_by('name')
serializer_class = HeroSerializer

5.2 Site URLs
Okay, awesome. We’re so close. The last step is to point a URL at the viewset we just created.
In Django, URLs get resolved at the project level first. So there’s a file in mysite directory called urls.py.
Head over there. You’ll see the URL for the admin site is already in there. Now, we just need to add a URL for our API. For now, let’s just put our API at the index:
from django.contrib import admin
from django.urls import include
from django.urls import pathurlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapi.urls')),
]

5.3 API URLs
If you’re paying attention and not just blindly copy-pasting, you’ll notice that we included 'myapi.urls'
. That’s a path to a file we haven’t edited yet. And that’s where Django is going to look next for instructions on how to route this URL.
So, let’s go there next — myapi/urls.py:
# myapi/urls.py
from django.urls import include, path
from rest_framework import routers
from . import viewsrouter = routers.DefaultRouter()
router.register('heroes', views.HeroViewSet)# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

The REST Framework router will make sure our requests end up at the right resource dynamically. If we add or delete items from the database, the URLs will update to match. Cool right?
So far, we’ve only added one model/serializer/view group to the router — heroes. But we can add more in the future repeating the same process above for different models!
Test it out!
Start up the Django server again:
python manage.py runserver
Now go to localhost:8000

Visit the endpoint via GET
If we click the link (Hyperlinks are good REST-ful design, btw), we see the heroes API results:

GET an Individual Hero
We can GET a single model instance using its ID.
Django REST Framework viewsets take care of this for us.
If you go to 127.0.0.1:8000/heroes/<id>/
where <id>
is the ID of one of your Heroes models, you’ll be able to see just that hero.
For example, http://127.0.0.1:8000/heroes/1/ for me returns:

We can make this a little more user-friendly by adding ID into the heroes/
endpoint response. In myapi/serializers.py
, change the fields list to include “id”:
fields = ('id','name', 'alias')

Now the hero list looks like this:

Send a POST request
Our API also handles post requests. We can send JSON to the API and it will create a new record in the database.

That’s it. You are done with your first API!
Definitely, it will get more complex as you add more models, but the concept remains the same.