Django Rest API – From Scratch – Part 1
Let’s create a todo app quickly

Project Setup
Create a directory where all your project files and environment exist.
mkdir django-rest
cd django-rest
You shouldn’t install any python
module globally because every project has different dependencies. The dependencies should be installed in the scope of a project. Therefore, you should create a virtual environment and activate it as following.
python -m venv env
source env/Scripts/activate
For windows
env\Scripts\activate
Install django
and djangorestframework
pip install django djangorestframework
Inside the current folder, you should create a django
project. A django
project is like a container to different web apps inside it. So, we have to create at least a web app.
django-admin startproject tutorial
cd tutorial
python manage.py startapp todo
Django creates an initial migration about authentication during the process of project creation. Migration is done for Object Relational Mapping (ORM), i.e. we map our classes to the structure of database. Hence, migrate the initial migration created.
python manage.py migrate
Django provides a powerful authentication, authorization mechanism. Not only that, it provides a robust admin panel for CRUD operation. Therefore, you can utilize the feature and create a superuser.
python manage.py createsuperuser
Here, I have created a superuser with username
and password
as nepcodex
Serializers
Create new python
module tutorial/todo/serializers.py
and paste the following lines of code
from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'groups'] class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ['url', 'name']
Views
Now, we have to write some views. You should understand that views in django
is different from views in other frameworks. Having said so, django
offers controlling in views and views in template. So, open tutorial/todo/views.py
and paste the following lines of code.
from django.contrib.auth.models import User, Group from rest_framework import viewsets from .serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializer
URLs
We have to wire up our API using automatic url routing. So, tet’s start mapping URLS. Open tutorial/tutorial/urls.py
and add some codes.
from django.urls import include, path from rest_framework import routers from todo import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) # 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')) ]
Pagination
Showing all the results in a single page is resource consuming and a slower process. Hence, you must limit the number of results to show when a request for the resource is opened. Therefore, open tutorial/tutorial/settings.py
and add follwing lines of code
REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10 }
Register
Finally, you have to register your app. This can be done in the beginning, if you want. So, open tutorial/tutorial/settings.py
and register rest_framework
as
INSTALLED_APPS = [ ... 'rest_framework', ]
Testing
Browse the url http://127.0.0.1:8000/ to check the API. You can see the list of urls in json format. You can browse those urls from your browser. Also, you can use API endpoints testing tools like Postman as well.
Summary
We can conclude total work done in following points:
- Created a directory
django-rest
where all our environment and project resides - Created a virtual environment
env
and activated it - Installed required
python
packagesdjango
anddjangorestframework
- Started a new
django
project namedtutorial
and inside it created an apptodo
- Migrated the initial migrations to database
- Created a superuser
- Added a new module named
serializers.py
to serialize data in json format needed for the API - Created viewsets inside
views.py
that are needed to view the data as a set - Wired up our API using automatic url routing
- Limited the number results using pagination in
settings.py
file - Registered the
rest_framework
insettings.py
- Tested the endpoints in browser or Postman.
If your app didn’t run successfully, then you can review the above points. You can start from the beginning and identify what might be missing.
If you already have successfully completed up to here, then let’s move into part 2 from here: https://nepcodex.com/blog/2019/07/django-rest-api-from-scratch-part-2/
Get Postman here: https://www.getpostman.com/downloads/