Create an API in Django Python
In this tutorial, we will be learning how to create an API in Django using REST framework.
API stands for Application Program Interface. It is a collection of software functions used to communicate between two software without user interference. It is very helpful to complete any task.
We can consider an example – you want to go to the tenth floor in a building, you can use stairs but instead you choose lift. You will call a lift using a button, lift will land you will press 10 and you will reach on the tenth floor. Here, lift works as an API. It is an intermediate function that helps software and web apps to exchange data. Here we will work and get JSON data from the objects.
Implementation of API in Django REST
Let’s start the coding part and learn how to implement API in Django REST. REST is a powerful tool used to create API, it has a lot of features that make it appropriate to create API.
Set up the folder and virtual environment to work on, for this you have to execute the following code on your machine in your terminal.
mkdir codespeedytutorial cd codespeedytutorial python -m venv env env\scripts\activate
This code will take you into a virtual environment.
Now install Django, Djangorestframework in the virtual environment you just created.
pip install django pip install djangorestframework
Create a project and start an app to work with API.
django-admin startproject api_project django-admin startapp api_app
You need to make sure that your api_app is inside the directory api_project.
After that, you need to make migrations and then migrate. Run the following commands in your terminal.
python manage.py makemigrations python manage.py migrate
The next step is to create a superuser to get all the access. For this, you need to write python manage.py createsuperuser and then it will ask you for a username, email, password, enter all your details and validate if it asks. You might need to enter it on the admin page so remember the username and password.
Serializers are used to convert the objects into some other appropriate models like JSON as when we send some data over the HTTP response we send the raw HTML, CSS, JS page. In the same way, we need to convert objects into an authorized form such as JSON. We have ModelSerializers to do this task. We will be considering the two objects Users and Groups which will be displayed in the form of a view in our browser. So let us move on and start working.
For this, you need to make a file named serializers.py inside your api_app.
Once you have created serializers.py you need to serialize it using the Rest framework. So, you need to import rest_framework and also users and groups.
We will use HyperlinkedModelSerializers which is quite different from the ModelSerializer. A HyperlinkedModelSerializers functions on the hyperlinks instead of primary keys which is a plus point in itself.
from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username'] class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ['url', 'name']
We have used two models named User, Group and the fields we need to display. We will only get the above fields in the display page in the browser.
A view(in this context) is a function that returns a JSON document. We need to show our data in JSON format, this is what our API is supposed to do. We will display all the fields we have created.
For this, you need to go to the views.py and append the below code. So that we can see the output in the JSON format.
from django.shortcuts import render from django.contrib.auth.models import User, Group from rest_framework import viewsets from myapiapp.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): queryset = Group.objects.all() serializer_class = GroupSerializer
First, we need to import User and Group and then viewsets from rest_framework. A viewset is a view that provides functions such as .list() and .create().
So, we have established the serializer and views but we don’t have a URL to get access to it. We need to specify a path to see the JSON data we have created. You guessed it right, we haven’t provided a path to surf into the data. Open urls.py and write the below code.
from django.urls import include, path from rest_framework import routers from myapiapp import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
Now, as everything is done we need to open the browser and append /users in the URL or you can visit http://127.0.0.1:8000/users or write groups instead of users for group data to see the data we have appended. You can also add data and then it will be displayed. The page will somewhat look like this:
Hope you enjoyed reading this tutorial, feel free to share your reviews and comment if you have any doubts.
KEEP READING! KEEP CODING