Building Restful Apis With Django Rest Framework

Building RESTful APIs with Django REST Framework

Hello Python enthusiasts! We are about to delve into the intricate and exciting world of creating RESTful APIs using Django REST framework. Whether you are a newbie or seasoned, this tutorial is designed to cater to all levels of Python users. This guide provides a comprehensive walk-through, aided by clear explanations, practical examples, and reliable sources to make your journey as smooth as possible.


Building Restful Apis With Django Rest Framework
Building Restful Apis With Django Rest Framework

Getting started: Understanding REST and Django

Before we start building, let’s define some key terms:

  • REST: Representational State Transfer (REST) is an architectural style that defines a set of constraints for creating web services.
  • API: Application Programming Interface (API) is a set of procedures for creating software applications.
  • Django: Django is a Python-based free and open-source web framework that follows the model-template-views (MTV) architectural pattern.

Django REST framework, often abbreviated as “DRF”, is a powerful toolkit for building RESTful APIs. It is flexible, secure, and comes bundled with features like serialization, query parameters, pagination, and user authentication.

Setup Environment

To start, we need to ensure that Python is installed on your system. You also need pip, which is a package management tool for Python. You can verify if these are installed by typing these commands into your terminal or command prompt:

python --version
pip --version

If Python or pip isn’t installed, refer to the Python official guide for installation steps. Once installed, we can now install Django and the Django REST framework:

pip install django
pip install djangorestframework

Creating Django REST Project

We will start by creating a new Django project:

django-admin startproject my_api

Then, go inside the project directory:

cd my_api

Now, let’s create an application in our project:

python manage.py startapp my_app

We now need to register my_app and rest_framework to the INSTALLED_APPS setting of your Django project (located in the settings.py file). Your code should look like this:

INSTALLED_APPS = [
    ...
    'my_app',
    'rest_framework',
]

Building Models

Models define the structure of the database. In my_app/models.py file, let’s define a simple model:

from django.db import models

class Stock(models.Model):
    symbol = models.CharField(max_length=12, primary_key=True)
    volume = models.IntegerField()

    def __str__(self):
        return self.symbol

Now, let’s run migrations to create our database schema:

python manage.py makemigrations
python manage.py migrate

Serializers

Serializers allow complex data types to be converted to Python data types. Let’s create a serializer for our Stock model:

# my_app/serializers.py

from rest_framework import serializers
from .models import Stock

class StockSerializer(serializers.ModelSerializer):
    class Meta:
        model = Stock
        fields = ['symbol', 'volume']

Viewsets and Routers

Viewsets abstract the logic of the views and provide expressiveness of the class-based views. Routers in Django REST framework allow creating simple and elegant URL configurations.

Replace the content of my_app/views.py with the following code:

# my_app/views.py

from rest_framework import viewsets
from .models import Stock
from .serializers import StockSerializer

class StockViewSet(viewsets.ModelViewSet):
    queryset = Stock.objects.all()
    serializer_class = StockSerializer

Next, we need to register our ViewSet with the router in my_api/urls.py:

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from my_app.views import StockViewSet

router = DefaultRouter()
router.register(r'stocks', StockViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

Now we’re ready to start the development server:

python manage.py runserver

You can now interact with your API at http://localhost:8000/stocks/.

FAQs

  1. What does REST stand for?
  2. REST stands for Representational State Transfer.

  3. What is Django used for?

  4. Django is used for web development.

  5. How do I start a new Django project?

  6. Using the command django-admin startproject projectname.

  7. How do serializers work in Django?

  8. They convert complex data types to Python data types.

  9. What is the purpose of Viewsets in Django REST framework?

  10. They abstract the logic of views and provide expressiveness of class-based views.

Conclusion

Building a RESTful API with the Django REST Framework is not only efficient but also provides built-in features that make the process straightforward and enjoyable. We hope this comprehensive guide has helped you understand and hone the art and science of creating robust REST APIs with Django.

References

Please leave your thoughts, feedback, and any questions you might have in the comments section. Happy coding!

Share this article:

Leave a Comment