Here’s a comprehensive Django REST Framework (DRF) cheat sheet formatted for pasting into a WordPress blog. It covers everything from setup to authentication and deployment, using standard WordPress-friendly HTML and code block formatting.
π§ Django REST Framework (DRF) Cheatsheet β Full Reference
This is your ultimate quick reference guide to Django REST Framework, from project setup to deploying a secure API.
π¦ 1. Project Setup
# Install packages
pip install django djangorestframework
# Start a Django project
django-admin startproject myproject
cd myproject
# Start an app
python manage.py startapp api
settings.py
:
INSTALLED_APPS = [
...
'rest_framework',
'api',
]
π§± 2. Models (Example)
# api/models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
python manage.py makemigrations
python manage.py migrate
𧬠3. Serializers
# api/serializers.py
from rest_framework import serializers
from .models import Post
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = '__all__'
π§ 4. Views
Option 1: APIView
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Post
from .serializers import PostSerializer
class PostList(APIView):
def get(self, request):
posts = Post.objects.all()
serializer = PostSerializer(posts, many=True)
return Response(serializer.data)
Option 2: Generic Views
from rest_framework import generics
class PostListCreate(generics.ListCreateAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
Option 3: ViewSets
from rest_framework import viewsets
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
π§ 5. URLs
# api/urls.py
from django.urls import path, include
from .views import PostListCreate
from rest_framework.routers import DefaultRouter
from .views import PostViewSet
router = DefaultRouter()
router.register(r'posts', PostViewSet)
urlpatterns = [
path('posts-list/', PostListCreate.as_view()), # generic view
path('', include(router.urls)), # viewset
]
# project/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
]
π‘οΈ 6. Permissions & Auth
Default Permission in settings.py
:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
Basic Permission Classes:
from rest_framework.permissions import IsAuthenticated, AllowAny
class MyView(APIView):
permission_classes = [IsAuthenticated]
π 7. Authentication Methods
Enable Token Auth:
pip install djangorestframework-simplejwt
# settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
]
}
Token URLs:
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns += [
path('api/token/', TokenObtainPairView.as_view()),
path('api/token/refresh/', TokenRefreshView.as_view()),
]
π§ͺ 8. Testing APIs with curl
or Postman
Get All Posts:
curl -X GET http://localhost:8000/api/posts/
Create a Post (JWT Auth):
curl -X POST http://localhost:8000/api/posts/ \
-H "Authorization: Bearer <your_token>" \
-H "Content-Type: application/json" \
-d '{"title": "Test", "content": "Hello"}'
βοΈ 9. Pagination
# settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
π§Ή 10. Filtering, Searching, Ordering
pip install django-filter
# settings.py
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': [
'django_filters.rest_framework.DjangoFilterBackend',
'rest_framework.filters.SearchFilter',
'rest_framework.filters.OrderingFilter',
]
}
# views.py
class PostViewSet(viewsets.ModelViewSet):
...
filterset_fields = ['title']
search_fields = ['title', 'content']
ordering_fields = ['created_at']
Usage:
GET /api/posts/?search=hello
GET /api/posts/?ordering=-created_at
π€ 11. Deployment Tips
- Use
WhiteNoise
for static files. - Set
DEBUG=False
and addALLOWED_HOSTS
. - Use
gunicorn
+nginx
or Cloud Run for serverless hosting. - Donβt forget to run:
python manage.py collectstatic
π 12. Useful DRF Links
- π DRF Official Docs
- π Simple JWT
β Final Words
DRF is incredibly powerful when you master its building blocks. Bookmark this cheat sheet for your next API project!