How To Create REST API Using Django


What is a REST(Representational State Transfer) API?

API is the way by which systems communicate with each other. APIs can be used for various purposes, such as accessing web services, retrieving data from databases, or connecting different components of a software application. Rest API (also known as RESTful API) use standard HTTP methods (GET,PUT,PATCH,DELETE,POST) to perform operations. They are widely used in web development. It uses JSON(JavaScript Object Notation) as its message format which is platform independent language.

Their are different types of web APIS eg. (SOAP which uses XML as their message format, Open APIs or public APIs that are accessible to external developers and general public.)

Well their are so many public APIs to use for many purposes. But you can create your own APIs as well and now we'll understand how to make it using Django .

Making REST API using Django

  • Installation :

  1. Make a virtual environment to make things separate from system.

  2. Activate it and install Django and Django-rest-framework.

  3. Make a new Django project .

     python3 -m venv venv 
     ./venv/bin/activate #to activate it 
     pip install djangorestframework #this will also install django and djangorestframework
     django-admin startproject <project name>
     python manage.py startapp api #making your app
     python manage.py runserver #server started at localhost:8000
    
     python manage.py makemigrations
     python manage.py migrate
     python manage.py createsuperuser #to access the admin panel
     python manage.py runserver #go to localhost:8000/admin/
    
  • Making model and changing settings :

  1. We'll create a basic model for students with name and age only.

  2. Go to the Settings.py file in the project folder and add your App name and package to it.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'api', #added app name
    'rest_framework' #installed package
]
  1. Create models in models.py in api app.
from django.db import models
​
class Student(models.Model):
    name = models.CharField(max_length = 250)
    age = models.IntegerField()

    def __str__(self):  #for convenience in the admin panel
        return self.name
  1. Now run these commands in terminal to migrate the the created model to Database.
python manage.py makemigrations
python manage.py migrate
  1. Add some random data in the admin panel at localhost:8000/admin.

  2. Create a new file serializers.py in the api app. Serializers.py basically serializes the data which you want to get or post in the JSON format.

from .models import Student
from rest_framework import serializers
​
​
class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student #the model which you want to serialise
        fields = '__all__' #fields you want. if want to add specific field do this ['field1','field2']
  1. Now in the views.py and add your logics.
from django.shortcuts import render
from rest_framework import generics
from .models import Student
from .serializers import StudentSerializer
​
class StudentView(generics.ListCreateAPIView):
    queryset = Student.objects.all() #same like sql queries
    serializer_class = StudentSerializer #serialising the data
  1. Now in the urls.py add your routes.
from django.urls import path,include
from .views import StudentView
​
urlpatterns = [
    path('student/',StudentView.as_view(),name='student'),
]
  1. Now you can test your created url in Browser. Just simply open the browser and type 127.0.0.1:8000/student/ and all set !

  2. Here, You can get as well post a new data of student.

Conclusion :

In this way you can create APIs using Django. You can add logic as well to protect your data, add specific logic for your data. You can read official documentation for more knowledge.