Building a REST API with Python and Django Rest Framework

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setting up Django
  4. Creating a Django App
  5. Defining Models
  6. Serializing Data
  7. Creating Views
  8. URL Routing
  9. Testing the API
  10. Conclusion

Introduction

In this tutorial, we will learn how to build a REST API using Python and Django Rest Framework. A REST API, or Representational State Transfer Application Programming Interface, allows applications to communicate with each other over the internet by sending and receiving data in a standardized format.

By the end of this tutorial, you will have a fully functional REST API that allows you to create, read, update, and delete resources from a database. We will cover the following topics:

  • Setting up Django
  • Creating a Django app
  • Defining models
  • Serializing data
  • Creating views
  • URL routing
  • Testing the API

Before we begin, make sure you have a working knowledge of Python and Django basics.

Prerequisites

To follow along with this tutorial, you will need the following:

  • Python installed on your machine
  • Django framework installed (we will install it later)
  • Basic knowledge of Python and Django concepts

Setting up Django

To get started, we need to install Django framework. Open your terminal and run the following command: bash pip install django Once Django is installed, you can create a new Django project by running the following command: bash django-admin startproject myproject This will create a new directory called myproject, which contains the basic files and folders for a Django project.

Navigate to the project directory: bash cd myproject You can now start the development server: bash python manage.py runserver Open your web browser and visit http://localhost:8000 to ensure the server is running correctly. You should see a Django welcome page.

Creating a Django App

In Django, a project is made up of one or more apps. Each app represents a specific functionality of the project. We will create a new app called api to handle our REST API.

Inside the project directory, run the following command: bash python manage.py startapp api This will create a new directory called api, which contains the necessary files for our app.

Add the newly created app to the INSTALLED_APPS list in the settings.py file: ```python # settings.py

INSTALLED_APPS = [
    ...
    'api',
    ...
]
``` ## Defining Models

Models in Django represent the structure of the database tables. We define models as Python classes, and Django automatically creates the database tables based on these classes.

Open the models.py file inside the api directory and define a simple model: ```python # models.py

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    pub_date = models.DateField()

    def __str__(self):
        return self.title
``` In this example, we have defined a `Book` model with three fields: `title`, `author`, and `pub_date`. The `__str__` method defines how the book object should be displayed as a string.

To create the database tables for our models, run the following command: bash python manage.py makemigrations python manage.py migrate

Serializing Data

Django Rest Framework provides a powerful serialization module that allows you to convert complex Python objects into JSON format. We will use this module to serialize our models.

Create a new file called serializers.py inside the api directory and define a serializer for the Book model: ```python # serializers.py

from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'
``` The `BookSerializer` class inherits from `serializers.ModelSerializer` and specifies the model and fields to include in the serialization.

Creating Views

Views in Django handle the logic for processing HTTP requests from clients. In our case, the views will handle the CRUD operations for our Book model.

Open the views.py file inside the api directory and define the view sets: ```python # views.py

from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
``` The `BookViewSet` class inherits from `viewsets.ModelViewSet`, which automatically provides the standard CRUD operations (list, create, retrieve, update, delete) for our `Book` model.

URL Routing

To associate our views with specific URLs, we need to define the routing configuration.

Open the urls.py file inside the myproject directory and update it as follows: ```python # urls.py

from django.urls import include, path
from rest_framework import routers
from api.views import BookViewSet

router = routers.DefaultRouter()
router.register(r'books', BookViewSet)

urlpatterns = [
    path('', include(router.urls)),
]
``` Here, we import the `BookViewSet` and register it with the router. Finally, we include the router URLs in our project URLs.

Testing the API

Now that we have set up our API, it’s time to test it.

Restart the development server if it’s not running. Open your web browser and visit http://localhost:8000/api/books/ to see a list of books (initially empty).

To create a new book, send a POST request to the same URL (http://localhost:8000/api/books/) with the required data in the body of the request.

To retrieve, update, or delete a specific book, send the corresponding HTTP request to http://localhost:8000/api/books/{book_id}/, where {book_id} is the ID of the book.

Congratulations! You have successfully built a REST API using Python and Django Rest Framework.

Conclusion

In this tutorial, we have learned how to build a REST API using Python and Django Rest Framework. We covered the basic steps, including setting up Django, creating a Django app, defining models, serializing data, creating views, and handling URL routing.

By following this tutorial, you should now have a solid foundation for building your own REST APIs with Python and Django. Remember to refer to the Django Rest Framework documentation for more advanced features and techniques.

Happy coding!