Building a RESTful API With Django REST Framework.

In this tutorial, I would be explaining how to build a todo RESTful API where user can perform a basic CRUD (CREATE, READ, UPDATE AND DELETE) operation.

Technologies Used

Below are the tools and technologies we would be using for building our RESTful API.

  1. Django
  2. Django REST Framework
  3. Postman  - A Chrome app that we'll use to practically test our API.

Introduction to REST API

REST

REST is acronym for REpresentational State Transfer. It is a software architectural style that defines a set of constraints to be used for creating Web services and was first presented by Roy Fielding in 2000 in his famous dissertation . Web services that conform to the REST architectural style are called RESTful Web services. The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service, a collection of other resources, a non-virtual object (e.g. a person), and so on.

API

An API is an application programming interface. It is a set of rules that allow programs to talk to each other. The developer creates the API on the server and allows the client to talk to it.

In a RESTful API, endpoints (URLs) define the structure of the API and how end users access data from our application using the HTTP methods: GET, POST, PUT, DELETE. Endpoints should be logically organized around collections and elements, both of which are resources.

GET - The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.

POST- The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.

PUT - The PUT method replaces all current representations of the target resource with the request payload.

DELETE- The DELETE method deletes the specified resource.

Let's dive in.

This article assumes

  • familiarity with Django and Python commands

  • you have Python,Django, and Postman installed.

I used VS Code as my editor as this is a free editor with many features and a built-in terminal which comes very handy for our use case. Feel free to use an editor of your choice.

Create a new django project

Go to favorite directory in your terminal and type the following command :

django-admin startproject Todoapi

A folder will be created by django with the name of your project. Open the new folder with the your favourite text-editor.

Your project folder should look like this

image.png

Install Django REST Framework

pip install djangorestframework

Once the Django Rest Framework has been installed, add it to the installed apps in your settings file (settings.py).

image.png

Create an App for your API.

Creating an API is also creating another Django web application. Therefore from your terminal create an application:

python manage.py startapp api

Add the name of your app to the installed apps in the settings.

image.png

Boom! Let's get our Api up and running.

Create your model

A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table.

Add the following code in your models.py:

     from django.db import models

     class Task(models.Model):
         title = models.CharField(max_length=200)
         completed = models.BooleanField(default=False, blank=True, 
                                  null=True)

         def __str__(self):
             return self.title

Register your model

In order to add items in the database, you should first register your model Task in the admin.py file and migrate your model.

     from django.contrib import admin
     from .models import Task
     # Register your models here.

    admin.site.register(Task)

Migrate your model

Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. Run the following commands in your command prompt

python manage.py makemigrations

python manage.py migrate

Create a Serializer

Here we are dealing with the data stored in a database which needs to be retrieved via web requests with the help of API. Therefore the best way of fetching the data is in the form of JSON. So we need to parse the data from database in JSON format. The serielizer does the job. Create a file named (serializer.py) in the api folder.

      from rest_framework import serializers
      from .models import Task

      class TaskSerializer(serializers.ModelSerializer):
          class Meta:
          model = Task
          fields = '__all__'

Create your View

A view function, or view for short, is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really.

In our first view,we will create a first view that lists all the URLs that are going to be exposed. We shall be using a decorator api_view provided by the rest framework. The @api_view decorator checks that the appropriate HTTP request is passed into the view function. Right now, we’re only supporting GET requests.

     from rest_framework.decorators import api_view
     from rest_framework.response import Response
     from .serializer import TaskSerializer

     from .models import Task
     # Create your views here.

    @api_view(['GET'])
    def apiOverview(request):
        api_urls = {
        'List': '/task-list/',
        'Detail View': '/task-detail/<str:pk>/',
        'Create': '/task-create/',
        'Update': '/task-update/<str:pk>/',
        'Delete': '/task-delete/<str:pk>/',
    }
        return Response(api_urls)

Lets configure our url

We are configuring URLs in the following approach.

  1. Create URL for api web app

  2. Link that api url to Django Project’s main URL

In urls.py in the Todoapi main folder add the following URL path:

    urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/',include('api.urls')),
]

Now create a new urls.py file in the api folder and add the following code:

     from django.urls import path
     from . import views

     urlpatterns = [
      path('', views.apiOverview, name="api-overview")

Your folder structure should be as shown below:

image.png

Run your server using python manage.py runserver and browse the url: 127.0.0.1:8000/api

image.png

Tada! We have our first api endpoint. This lists all the requests we can make to the API.

Now lets build other endpoints.

We will create different views for diffferent endpoints

  1. TaskList Function - list all the items from the database.
  2. AskDetail Function - list the details of items based upon the id.
  3. Create Function - create and store the new tems to database.
  4. Update and Delete- Update and Delete items.

In views.py add the following code:

      @api_view(['GET'])
      def taskList(request):
          tasks = Task.objects.all()
          serializer = TaskSerializer(tasks, many=True)
           return Response(serializer.data)

      @api_view(['POST'])
      def taskUpdate(request, pk):
          task = Task.objects.get(id=pk)
          serializer = TaskSerializer(instance=task, data=request.data)

          if serializer.is_valid():
              serializer.save()
         return Response(serializer.data)

      @api_view(['GET'])
       def taskDetail(request, pk):
             tasks = Task.objects.get(id=pk)
             serializer = TaskSerializer(tasks, many=False)
        return Response(serializer.data)

     @api_view(['POST'])
     def taskCreate(request):
         serializer = TaskSerializer(data=request.data)

         if serializer.is_valid():
            serializer.save()
         return Response(serializer.data)

     @api_view(['DELETE'])
     def taskDelete(request, pk):
         task = Task.objects.get(id=pk)
         task.delete()
         return Response("Task Deleted Successfully")

Update the urls.py in the api folder:

   urlpatterns = [
    path('', views.apiOverview, name="api-overview"),
    path('task-list', views.taskList, name="task-list"),
    path('task-detail/<str:pk>/', views.taskDetail, name="task-detail"),
    path('task-create/', views.taskCreate, name="task-create"),

    path('task-update/<str:pk>/', views.taskUpdate, name="task-update"),
    path('task-delete/<str:pk>/', views.taskDelete, name="task-delete"),
]
Let's populate our database.

Stop your server and run the command below Input

python manage.py createsuperuser

Your terminal will prompt you enter your username, email and password. After that go to 127.0.0.1:8000/admin and add a few tasks.

Test

Having done all these,We’re now ready for test!

Fire up the server and go to your postman or use your browser to test the endpoints created.

Output: image.png

Output: image.png

Output: image.png

Output: image.png

Output: image.png

Output: image.png

Conclusion

I hope you enjoyed this post and it helped you to build your first REST API using Django Rest Framework. Of Course, APIs can do much more complicated work with multiple models intersection and endpoints with more complex queries. But you are on the way and on driving seat, go drive and build something cool.