post cover

Building a REST API with Django

Building a REST API with Django

Django is a popular Python web framework that can be used to build web applications, including REST APIs. In this post, I’ll walk through creating a basic REST API using the Django REST Framework (DRF).

What is a REST API?

REST (Representational State Transfer) is an architectural style for building web APIs. A REST API allows clients to access and manipulate resources using HTTP requests. REST APIs typically provide data in JSON format and use standard HTTP methods like GET, POST, PUT, and DELETE.

Some fundamental principles of REST APIs:

  • Resources are accessed via standard URLs and HTTP methods
  • Requests are stateless and may be processed in any order
  • Resources can be represented in multiple formats like JSON, XML, etc.
  • Uses HTTP status codes to indicate API responses

Why Use Django for a REST API?

Django provides a robust framework for building web applications. Some key reasons to use it for REST APIs:

  • Object-relational mapper (ORM) makes it easy to interact with databases
  • Modular design allows you to build reusable components
  • Built-in admin interface helps manage content
  • Large open-source community provides solutions for everyday problems

Django REST Framework (DRF) is a popular Django library for building REST APIs. It handles things like serialization, view logic, authentication, and more.

Project Setup

Let’s build a simple REST API with Django and DRF from scratch. We’ll create an API to manage a list of “todos”.

First, create a new Django project and application:

# Create a project folder
mkdir django_todo
cd django_todo

# Create virtualenv
python3 -m venv .venv
source .venv/bin/activate

# Install Django and DRF
pip install django djangorestframework

# Create project
django-admin startproject api .

# Create app
cd api
python manage.py startapp todos

Now register the todos app and REST framework in settings.py:

# api/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    # ...
    'rest_framework',
    'todos',
]

Models

Next, we’ll create a Todo model with just a title and description field:

# todos/models.py

from django.db import models

class Todo(models.Model):
  title = models.CharField(max_length=120)
  description = models.TextField()

Run migrations to create the todo table in the database:

python manage.py makemigrations
python manage.py migrate

Serializers

We need serializers to convert model instances to and from JSON. DRF has a ModelSerializer that handles this for us:

# todos/serializers.py

from rest_framework import serializers
from .models import Todo

class TodoSerializer(serializers.ModelSerializer):
  class Meta:
    model = Todo
    fields = ('id', 'title', 'description')

Views

We can now create API views to handle GET, POST, PUT, and DELETE requests. DRF provides generic class-based views we can extend:

# todos/views.py

from rest_framework import generics
from .models import Todo
from .serializers import TodoSerializer

class ListTodo(generics.ListCreateAPIView):
  queryset = Todo.objects.all()
  serializer_class = TodoSerializer

class DetailTodo(generics.RetrieveUpdateDestroyAPIView):
  queryset = Todo.objects.all()
  serializer_class = TodoSerializer

This creates primary CRUD endpoints for /todos/ and /todos/:id/.

URLs

Wire up the API URLs:

# api/urls.py

from django.urls import path, include

urlpatterns = [
  path('api/v1/todos/', include('todos.urls')),
]
# todos/urls.py

from django.urls import path
from . import views

urlpatterns = [
  path('', views.ListTodo.as_view()),
  path('<int:pk>/', views.DetailTodo.as_view())
]

Testing API

Run the development server:

python manage.py runserver

We can now test our API using curl or a tool like Postman.

To list all todos:

GET /api/v1/todos/

Create a new todo:

POST /api/v1/todos/ { "title": "Walk dog", "description": "Take spike on a walk in the park" }

Update a todo:

PUT /api/v1/todos/1/ { "title": "Walk dog in the morning" }

Delete a todo:

DELETE /api/v1/todos/1/

And that’s it! In this post, we saw how to:

  • Create a Django project
  • Build a Todo model
  • Serialize data with DRF serializers
  • Create API views for CRUD operations
  • Handle URL routing
  • Test API endpoints

Django and DRF make it easy to quickly build a fully-featured REST API. You can do many additional things like add authentication, pagination, filtering, and more. This gives you a good starting point for building your APIs with Django!