Django framework has become one of the preferred frameworks of developers. It’s quite obvious as it handles data serialization and works seamlessly with Django’s ORM. That’s why Django is a powerful and flexible toolkit for building web APIs, including REST API.
REST API has become a standardized method to provide data to other applications. These applications further process the data and use it for various purposes. That’s why REST API is of critical importance and Django is a perfect platform to create one. In this blog post, we’re going to go through straightforward steps to develop REST APIs with Django Rest Framework (DRF). Let’s get started!
Steps Involved in Creating REST API with Django Framework
The process of creating REST APIs in the Django framework can be divided into five easy steps. It starts with setting up Django and finishes with creating URI endpoints. Here are they:
Install Django & set up a new project
Create a model in the database for Django ORM
Set up the Django REST Framework
Serialize the models
Create the URI endpoints to view the serialized data
Seems simple enough, doesn’t it? Let’s get started then!
Step 1: Install Django Framework
The first obvious and easiest step involved in this process is installing the Django framework. We’d suggest you create a new virtual environment for your project as it allows you to manage dependencies separately.
We’re going to use pyenv, a simple Python management tool, to create a virtual environment. It’s quite a convenient tool as it allows you to change global Python versions, install multiple Python versions, set project-specific Python versions, and manage virtual Python environments.
1. Install Pyenv
2. Define Environment Variable
Now we need to define the environment variable PYENV_ROOT to point to the path where pyenv repo is cloned. Then, add $PYENV_ROOT/bin to the $PATH for access to the pyenv command-line utility.
$ pyenv virtualenv django-rest
Looking in links: /tmp/tmpjizkdypn
Requirement already satisfied: setuptools in/home/bennett/.pyenv/versions/3.6.8/envs/django-rest/lib/python3.6/site-packages (40.6.2)
Requirement already satisfied: pip in
$ pyenv local django-rest
4. Install Python & Create a Virtual Environment
Apply the below command to install the latest python version. Please note that 3.10.0 is the latest version as of the date we’re writing this article. Thus you will need to install the one latest whenever you are trying to install.
$ pyenv install 3.10.0
To create an environment for the project:
$ pyenv virtualenv 3.7.4 blog
5. Create a Django Project
Now, apply the below command to create a project:
$ django-admin startproject mysite
To verify the project creation, go to the directory and you will find a new folder there:
Now go inside the folder to find everything you need to run a site:
$ cd mysite/$ lsmanage.py* mysite/
6. Test Run Django Server
Use the below command to see if it works or not:
$ python manage.py runserverWatching for file changes with StatReloaderPerforming system checks...System check identified no issues (0 silenced).You have 17 unapplied migrations. The project may not work properly until you apply the migrations
for apps: admin, auth, contenttypes, sessions.Run 'python manage.py migrate' to apply them.May 17, 2019 - 16:09:28Django version 2.2.1, using settings 'mysite.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.
You can go to the localhost:8000 and see the Django welcome screen. Easy first step, wasn’t it?
7. Create API App
For the ease of use and management, we will separate the Django project into separate apps. Here’s how you can create a new API app:
As you can see, we’ve named it ‘myapi.’
8. Connect API App with Django and Register the Project
Now that we’ve created an API app, we now need to connect Django to it and register with the project we just created.
To do so, we first need to edit the mysite/settings.py and apply the following:
INSTALLED_APPS = ['myapi.apps.MyapiConfig',... # Leave all the other INSTALLED_APPS]
9. Migrate Models to the database
Once we create or make changes to a model, we need to tell Django to migrate those changes to the database. Moreover, Django has its own built-in models, and thereby we need to migrate them to our database.
If you’re wondering that we forgot to create a database, then don’t worry. Django creates SQLite databases on its own, and it’s more than good enough.
Apply the following to migrate the models:
After adding models and installing the REST framework, the next important step is to set up the DRF serializers. It will turn the Personal model and species into JSON, which the API can employ to transfer the data back to the user.
To serialize the models, we need to create a new file myapi/serializers.py.
from rest_framework import serializers
from myapi.models import Person, Species
class PersonSerializer(serializers.ModelSerializer):class Meta:model = Personfields = ('name', 'birth_year', 'eye_color', 'species')
class SpeciesSerializer(serializers.ModelSerializer):class Meta:model = Speciesfields = ('name', 'classification', 'language')
Step 5: Create API URLs
The 5th and final step is to create a view to the API and connect to the Django URLs. For that, we need to add two viewsets of each model we created. Here’s how you can do it:
from rest_framework import viewsets
from myapi.serializers import PersonSerializer, SpeciesSerializerfrom myapi.models import Person, Species
class PersonViewSet(viewsets.ModelViewSet):queryset = Person.objects.all()serializer_class = PersonSerializer
class SpeciesViewSet(viewsets.ModelViewSet):queryset = Species.objects.all()serializer_class = SpeciesSerializer
Now that we’ve created the viewsets, we now need to route the API endpoint to a viewset. For that, first create a new file myapi/urls.py and add the router configuration as shown below.
from django.urls import include, path
from rest_framework import routers
from myapi.views import PersonViewSet, SpeciesViewSet
All done? Now the URL encompasses all the API methods (GET, POST and PUT). Now it’s time to test the API and see how it works!
Step 6: Test the API
Next, go to the http://127.0.0.1:8000/test-project/species/, and you will be able to use the API where you can add species. You can add the species and see if you get 201 success messages in return.
Et voila! You have successfully deployed the REST API using Django Framework. Now you see why many prefer Django development, don’t you? It’s fast and doesn’t make a lot of fuss.
Inexture Solutions: Next Gen Django Development Company
Many people ask us why we prefer Django so much when most of the developers are preferring other frameworks. We have a simple answer to that, and it’s that we like to stay a step ahead. We, at InExture, not only like to keep pace with the latest happenings but also peek into the future to use the best technologies.
We pride ourselves in our Django developers and Python development services we offer. We’ve got a stellar portfolio and would love to be a part of your next endeavour. Let’s get in touch!