How to Create a basic API using Django Rest Framework ?
Django REST Framework (DRF) is a powerful extension of Django that helps you build APIs quickly and easily. It simplifies exposing your Django models as RESTfulAPIs, which can be consumed by frontend apps, mobile clients or other services.
Before creating an API, there are three main steps to understand:
- Serialization: Convert complex data like Django models/querysets into JSON or XML format.
- Viewsets: Define views that handle API requests and responses.
- URL Routing: Map URLs to your API views so they can be accessed by clients.
This article will teach you how to implement Django REST framework to easily create API endpoints by building a simple CRUD (Create, Read, Update, Delete) API for a Book model with three fields: title, author and publish_date.
Refer to the following articles to check how to create a project and an app in Django.
Step 1: Add DRF to Installed Apps
In your settings.py, add 'rest_framework' and you 'app' to INSTALLED_APPS to enable DRF in your Django project:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'app'
]
Also make sure to install Django restframework module if it isn't already installed using command:
pip install djangorestframework
Step 2: Create the Book Model
In app/models.py, define the Book model with three fields:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
publish_date = models.DateField()
def __str__(self):
return self.title
- CharField is used for short text (title, author).
- DateField stores the date when the book was published.
- __str__ method returns a human-readable representation of each book instance.
Step 3: Create a Serializer
Serializers convert model instances into JSON and validate incoming JSON data. Create app/serializers.py:
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ['id', 'title', 'author', 'publish_date']
- ModelSerializer automatically generates fields based on the model.
- fields tuple specifies which model fields to expose via the API.
- id field (primary key) is included to uniquely identify each record.
Step 4: Define a ViewSet
ViewSets provide CRUD operations in one place. In app/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
- ModelViewSet automatically provides list, retrieve, create, update and destroy actions.
- queryset defines the set of objects available via the API.
- serializer_class tells DRF how to serialize/deserialize the Book data.
Step 5: Configure URLs with a Router
DRF routers automatically generate URL patterns for your ViewSets. Create app/urls.py:
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import BookViewSet
router = DefaultRouter()
router.register(r'books', BookViewSet)
urlpatterns = [
path('', include(router.urls)),
]
Using DefaultRouter, you don’t need to manually define each URL for CRUD operations. It automatically creates standard RESTful endpoints like:
- GET /books/ (list all books)
- POST /books/ (create new book)
- GET /books/{id}/ (retrieve a single book)
- PUT /books/{id}/ (update a book)
- DELETE /books/{id}/ (delete a book)
Including these URLs in your main projectName/urls.py will expose the API.
Step 6: Migrate and Run the Server
Run the following commands to create your database tables and start the server:
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
You can now:
- See a list of books (empty at first)
- Use POST requests to add new books
- Access individual books, update or delete them using standard HTTP methods
Accessing the API Endpoints:
Because in your projectName/urls.py you included your app’s URLs with the prefix api/, all your API endpoints will be accessed through URLs starting with /api/.
For example, the DefaultRouter in your app/urls.py registered the BookViewSet with the route books. So, the endpoints you can use are:
HTTP Method | Endpoint URL | Description |
---|---|---|
GET | http://127.0.0.1:8000/api/books/ | List all books |
POST | http://127.0.0.1:8000/api/books/ | Create a new book |
GET | http://127.0.0.1:8000/api/books/{id}/ | Retrieve a book by its ID |
PUT | http://127.0.0.1:8000/api/books/{id}/ | Update a book by its ID |
DELETE | http://127.0.0.1:8000/api/books/{id}/ | Delete a book by its ID |
Note:
Replace {id} with the actual book ID you want to retrieve, update or delete.
The /api/ prefix is required because you included your app URLs under path('api/', include('app.urls')) in the main urls.py.
Output:
Below is the snapshot of the /books/ endpoint after adding some entries:

Let's look at the options we get when we navigate the /book/{id}/ with id of some book:

In the above snapshot, we are getting the options of performing all the CRUD operations, which means out app is working fine.