Create a REST API Using Django REST Framework

As a Python developer, I’ve found Django to be one of the most powerful frameworks for building APIs quickly and efficiently. In this article, I’ll walk you through how to create a RESTful API in Python Django using Django Rest Framework (DRF), sharing practical tips and full code examples.

If you’re looking to build APIs for real-world applications, like managing a product catalog for a US-based e-commerce site or handling user data for a service, you’re in the right place.

Let’s get in!

What You Need Before We Start

Before we jump into coding, make sure you have:

  • Python installed (version 3.6+ recommended)
  • Django installed (pip install django)
  • Django Rest Framework installed (pip install djangorestframework)
  • Basic understanding of Python and Django

Check out Create a Notes Taking app in Django

Step 1: Create a New Django Project

First, open your terminal and create a new Django project named usestoreapi (imagine we’re building an API for a US retail store):

django-admin startproject usestoreapi
cd usestoreapi

Step 2: Create a Django App

Inside your project, create a new app called products to manage product data:

python manage.py startapp products

Add the app and rest_framework to your INSTALLED_APPS in usestoreapi/settings.py:

INSTALLED_APPS = [
    # default apps...
    'rest_framework',
    'products',
]

Read Build a To-Do List API in Django Rest Framework

Step 3: Define the Product Model

In products/models.py, define a simple product model with fields relevant to a US store inventory:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    in_stock = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

Run migrations to create the database tables:

python manage.py makemigrations
python manage.py migrate

Step 4: Create a Serializer

Serializers convert model instances to JSON so your API can communicate with clients. Create a file products/serializers.py:

from rest_framework import serializers
from .models import Product

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

Step 5: Build API Views

I prefer using DRF’s generic views for simplicity and speed. In products/views.py, add:

from rest_framework import generics
from .models import Product
from .serializers import ProductSerializer

class ProductListCreate(generics.ListCreateAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

class ProductDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

These views allow:

  • Listing all products and creating new ones (ProductListCreate)
  • Retrieving, updating, or deleting a specific product (ProductDetail)

Read Use Django Built-In Login System

Step 6: Configure URLs

Create a products/urls.py file and add:

from django.urls import path
from .views import ProductListCreate, ProductDetail

urlpatterns = [
    path('products/', ProductListCreate.as_view(), name='product-list-create'),
    path('products/<int:pk>/', ProductDetail.as_view(), name='product-detail'),
]

Then, include these URLs in the main project’s usestoreapi/urls.py:

from django.contrib import admin
from django.urls import path, include

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

Step 7: Test Your API

Run the Django development server:

python manage.py runserver

Now, you can access:

  • http://localhost:8000/api/products/ — to GET all products or POST a new product
  • http://localhost:8000/api/products/<id>/ — to GET, PUT, PATCH, or DELETE a specific product

You can test these endpoints using tools like Postman or curl.

You can refer to the screenshot below to see the output.

how to create api in python Django

Check out Google Authentication in Django

Bonus: Add Filtering and Pagination

To make your API more user-friendly, especially for large US-based inventories, add filtering and pagination.

In usestoreapi/settings.py add:

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
}

Install filtering support:

pip install django-filter

Update INSTALLED_APPS:

INSTALLED_APPS += ['django_filters']

Modify your view in products/views.py:

from rest_framework import generics
from django_filters.rest_framework import DjangoFilterBackend
from .models import Product
from .serializers import ProductSerializer

class ProductListCreate(generics.ListCreateAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['in_stock', 'price']

Now you can filter products like /api/products/?in_stock=True or paginate results.

Read Print Django Environment Variables

Alternative Method: Use ViewSets and Routers

If you prefer a more compact approach, DRF’s ViewSets and Routers can automatically generate URLs.

Update products/views.py:

from rest_framework import viewsets
from .models import Product
from .serializers import ProductSerializer

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

Update products/urls.py:

from rest_framework.routers import DefaultRouter
from .views import ProductViewSet

router = DefaultRouter()
router.register(r'products', ProductViewSet)

urlpatterns = router.urls

This method reduces boilerplate and is great for larger APIs.

Creating APIs with Django and Django Rest Framework is simple once you get the hang of it. Whether you choose generic views or viewsets depends on your project needs. The examples above can be adapted for many use cases, from managing US retail inventories to user profiles or any data-driven application.

If you want to expand this API, consider adding authentication, permissions, and more complex filtering. But for now, you have a solid foundation to build on.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.