Creating a REST API with Django and Django REST Framework (DRF) is straightforward and powerful. In this tutorial, we’ll guide you step-by-step through the process of building your first REST API.
1. Setting Up the Environment
Install Django and DRF
- Create a virtual environment:
python3 -m venv venv
venv/Scripts/activate
- Install Django and DRF:
pip install django djangorestframework
2. Create a Django Project and App
Create a Project
django-admin startproject myproject
cd myproject
Create an App
python manage.py startapp myapp
Add myapp
and rest_framework
to the INSTALLED_APPS
in settings.py
:
INSTALLED_APPS = [
...
'rest_framework',
'myapp',
]
3. Create a Model
In myapp/models.py
:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
published_date = models.DateField()
isbn = models.CharField(max_length=13)
def __str__(self):
return self.title
Run migrations to apply the model:
python manage.py makemigrations
python manage.py migrate
4. Create a Serializer
In myapp/serializers.py
:
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
5. Create a View
In myapp/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
6. Create a Router
In myapp/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)),
]
Include the app’s urls.py
in the project’s urls.py
:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('myapp.urls')),
]
7. Test the API
Run the server:
python manage.py runserver
Visit http://127.0.0.1:8000/api/books/
to interact with your API:
- GET: Retrieve all books.
- POST: Add a new book.
- PUT/PATCH: Update an existing book.
- DELETE: Delete a book.
8. Add Authentication (Optional)
You can secure your API by adding token-based authentication.
- Install DRF’s token authentication:
pip install djangorestframework-simplejwt
- Update
settings.py
:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
- Add authentication endpoints in
urls.py
:
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns += [
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
9. Explore the API
You can use tools like Postman, Insomnia, or the DRF Browsable API for testing and interacting with your API.
Congratulations! You now have a fully functional REST API built with Django and Django REST Framework. This setup is simple yet flexible enough for most applications. Happy coding!