What's a REST API and how to build a simple REST API with Django.

First things first, what is an API?

  • Application Programming Interface

  • A mechanism that houses a collection of communication protocols and subroutines that allow two or more applications to communicate with each other.

What is a REST API?

REST (Representational State Transfer) is an API designed for networked applications that has a set of rules for building and interacting with services that follow the principles of REST.

  • Design Principles of REST:

    1. Uniform Interface

      All requests for the same resource should be identical. I.E same piece of data like name , contact details of the user, must be long to one uniform resource identifier. Resources must not be larger but should have ever necessary information the user could potentially need.

    2. Client-server decoupling

      • Client and server application should be separate and independent of each other.

      • Client only needs to the know the URI and it can’t talk to the server in any other way.

      • Server provides the requested information through the internet without messing up how the client works.

      • This allows the two to be more flexible and scalable and not rely on each other.

    3. Statelessness

      Each request must include all the required information for processing.

    4. Cacheability

      By caching information on a client’s device or the server, the application becomes faster and more scalable.

    5. Layered System Architecture

      The requests and responses must go through different stages, that way the client or server cannot tell whether it communications with the end or intermediary.

Parts of a REST API?

  • Resources:

    Resources are the fundamental entities or objects that the API exposes. They can be data objects, services, or anything that can be identified and manipulated. Each resource is uniquely identified by a URI (Uniform Resource Identifier).

  • URI (Uniform Resource Identifier):

    URIs are used to identify and locate resources on the web. They provide a unique address for each resource, allowing clients to interact with specific entities using standard HTTP methods.

  • HTTP Methods (GET, POST, PUT, DELETE, etc.):

    RESTful APIs use standard HTTP methods to perform different operations on resources. The primary methods include GET (retrieve), POST (create), PUT/PATCH (update), and DELETE (delete). These methods define the actions clients can take on resources.

  • Representation:

    Resources are represented in a specific format, such as JSON or XML. Representations convey the state of a resource and are exchanged between clients and servers during API interactions.

  • Headers:

    HTTP headers provide additional information about the request or response. They can include details like content type, authentication tokens, and caching directives. Headers play a crucial role in controlling and describing the communication between clients and servers.

  • Request and Response:

    A client sends a request to the server to perform an action on a resource, and the server responds with the result of that action. Requests and responses contain information such as the HTTP method, headers, and the resource representation.

  • Status Codes:

    HTTP status codes indicate the outcome of a request. Common status codes include 200 OK (successful), 201 Created (resource created), 404 Not Found (resource not found), and 500 Internal Server Error (server error). These codes help clients understand the result of their requests.

  • Authentication and Authorization:

    REST APIs often include mechanisms for authenticating and authorizing clients. This ensures that only authorized users can perform certain actions on resources. Common authentication methods include API keys, OAuth tokens, or other authentication tokens.

  • Endpoint:

    An endpoint is a specific URI that clients use to interact with a particular resource or a set of related resources. Endpoints are defined by the API and serve as entry points for various actions.

Why are they used?

  • REST APIs allow efficient scalability as REST optimizes client-server interactions. Because of the design principle statelessness, it discards server load, as past client request is not stored. In addition to that, the separation of the client and the server in the architecture allows developers to scale the application with ease.

  • REST APIs are flexible with handling varies data formats such as XML, JSON and so on.

  • REST APIs have strong and reliable security as it typically uses authentication through access tokens, these tokens are difficult to crack due to it’s uniqueness, and also the option to give implement other security measures like : HTTPS, input validation, cross origin resource sharing and etc.

The Django REST framework

The Django Rest Framework (DRF) is an additional package for Python’s Django Web Framework. On top of Django providing a strong foundation for building web applications, DRF focuses on building web APIs, and adds powerful tools and abstractions to simplify the process of developing RESTful APIs.

DRF offers features such as:

  • Serialization through serializers that provide conversion of instances or other data into representations suitable for APIs (JSON, XML)

  • API-centric views: Classes like APIView, GenericAPIView, ViewSet and ModelViewSet are designed for defining API endpoints efficiently

  • Routers: These Routers can automatically generate URLs for API endpoints based on ViewSets which simplifies configuration


Now that we understand APIs, REST APIs & Django REST Framework, let's build a simple one using Django.


Ensure that you have django and the django rest-framework installed.

To check if you have them install enter the commands

  • Django

      python -m django --version
    

    Should show you the current version of django that is installed in your machine.

    If you get the message "no module named 'django'", then simply enter the command

      pip install django
    

Django Rest-framework (DRF)

pip show djangorestframework

This will return information about the about the DRF package including the version number like below:

Name: djangorestframework
Version: 3.14.0
Summary: Web APIs for Django, made easy.
Home-page: https://www.django-rest-framework.org/
Author: Tom Christie
Author-email: tom@tomchristie.com
License: BSD
Location: //location
Requires: django, pytz
Required-by:

It won't return information if the DRF package isn't install

In the case it isn't installed enter the following command:

pip install djangorestframework

Create the project

In your command prompt, select the desired path, then enter the command to create the project:

python django-admin startproject myproject

Create the app

Now that you made the project, you create the app by first going into your project directory in cmd

cd myproject

then create the app with the following command

python manage.py startapp myapp

Your file structure should look like this:

File structure of your project.

Configure the INSTALLED_APPS list in settings.py

Add the app (myapp) and the rest framework into the INSTALLED_APPS list

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', 
    'rest_framework'
]

Configure the urls.py file

To be specific we'll be on the urls.py file on the myproject folder (refer to the image below)

We'll be importing the includes function from the django.urls module

from django.urls import path,include #note that path is already imported so just put ',include'

Next we'll be adding our 'myapp' app to our urlpatterns.

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

Check on the views.py

  • To ensure that the urls.py we configured is working let's make a simple view on the myapp folder

  • Make a simple view

      from django.shortcuts import render,HttpResponse
      # Create your views here.
      def home(request):
          return HttpResponse("Hello")
    

    Add that view to the urls.py file

      from django.urls import path
      from . import views
    
      urlpatterns =[
          path('',views.home,name='home')
    

    Ensure that you have imported the views

    You should be getting the following result when you entered

    python manage.py runserver

    Make sure that the entered URL is 127.0.0.1:8000/api/

Create a model

On the myapp folder, we'll be making a model called Item with two fields, name and description.

from django.db import models
class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    def __str__(self):
        return self.name

Register the Item model

In your admin.py file of the myapp app, register the Item model created in the models.py.

from django.contrib import admin
from .models import Item

# Register your models here
admin.register(Item)

Make the migrations

python manage.py makemigrations

python manage.py migrate

Create the serializers

  • Serializers are a crucial component in DRF. They assist in the conversation of complex data types into Python data types, that can be easily rendered into JSON or other content types, and they handle parsing incoming data in requests and validate it before processing.

  • To create them we need to make a new python file with the name serializers.py from there we enter the following code.

  •             from rest_framework import serializers
                from .models import Item
    
                class ItemSerializer(serializers.ModelSerializer):
                    class Meta:
                        model=Item
                        fields='__all__'
    

    serializers.ModelSerializer simplifies the process of working with django models, it automatically generates the serilizer fields based on the fields in a model, this removes the requirement to explicitly define each field in the serializer.

Configure the views.py files

  • Now create views for the REST api with the use of generics

      from rest_framework import generics
      from .models import Item
      from .serializers import ItemSerializer
    
      class ItemListCreateView(generics.ListCreateAPIView):
          queryset = Item.objects.all()
          serializer_class = ItemSerializer
    
      class ItemRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView):
          queryset = Item.objects.all()
          serializer_class = ItemSerializer
    
  • What are generics?

    • Generics provide a set of generic class-based views, they encapsulate common patterns and behaviors, making it easeir to create views for common operations on models

    • ListCreateAPIView

      • Provides the list (GET) and create (POST) operations for a model.

      • Commonly used for views that involve displaying a list of instances and creating new instances of a model.

    • RetrieveUpdateDestroyAPIView

      • Provides the retrieve (GET), update (PUT/PATCH), and destroy (DELETE) operations for a model instance.

      • Commonly used for views that involve displaying a single instance, updating it, or deleting it.

Run the server

After running python manage.py runserver and entered the api route, you will get this output.

127.0.0.1:8000/api/items/

127.0.0.1:8000/api/items/1

Testing the API

  • POST a new instance test
  • After POST of a new instance

    As you can see because of our view having the generic ListCreateAPIView

    We can only do GET and POST requests.

    DELETE, UPDATE & POST test

    Now with our Route being 127.0.0.1:8000/api/items/2/ where 2 is the primary key, we're allowed to request GET, PUT, PATCH & DELETE requests on a specific instance in our Item list.


Conclusion

In this article we looked over the basics of RESTful APIs, as well as building a simple one with Django and Django Rest Framework. We explored concepts such as the components to a REST API, the design principles it follows, the DRF and it's briefly went over it's features, and with the DRF we went to build a very simple one using serializers and generics from the DRF. Whether you're just starting with API development or looking to enhance your existing skills, the combination of Django and DRF provides a powerful framework for building modern, data-driven web applications.