How to Build a RESTful API with Django in 5 Easy Steps
Building a RESTful API with Django is easier than ever thanks to the Django REST Framework (DRF). This tutorial walks you through setting up a simple, functional API from scratch—no prior experience with DRF required.
1. Install and Setup a New Django Project
First, install Django and the Django REST Framework using pip:
pip install django djangorestframework- Create a project:
django-admin startproject myapi - Navigate into the project and create an app:
python manage.py startapp myapp
Add 'rest_framework' and 'myapp' to your INSTALLED_APPS in settings.py.
2. Define Your Model
In myapp/models.py, create a simple model to expose via your API:
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
Run python manage.py makemigrations and migrate.
3. Create a Serializer
Serializers convert complex data types (like Django models) into JSON. Create myapp/serializers.py:
from rest_framework import serializers
from .models import Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = '__all__'
4. Build the API Views and URL Route
In myapp/views.py, use DRF’s generic views to create a list and detail endpoint:
from rest_framework import generics
from .models import Item
from .serializers import ItemSerializer
class ItemList(generics.ListCreateAPIView):
queryset = Item.objects.all()
serializer_class = ItemSerializer
class ItemDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Item.objects.all()
serializer_class = ItemSerializer
In myapp/urls.py, map the views:
from django.urls import path
from .views import ItemList, ItemDetail
urlpatterns = [
path('items/', ItemList.as_view()),
path('items/<int:pk>/', ItemDetail.as_view()),
]
Include this in your project’s main URL config.
5. Test Your API
Run python manage.py runserver and visit http://127.0.0.1:8000/items/. You can now perform GET, POST, PUT, and DELETE requests—congratulations, you’ve created a full RESTful API!
Conclusion: With just a few components, Django REST Framework provides a powerful, production-ready way to expose data via RESTful endpoints. Experiment with permissions, pagination, and authentication to expand your API further.