</>
Skip to content
Django lessons (38/43)

Django — REST Framework

Installation

pip install djangorestframework

Setup

# settings.py
INSTALLED_APPS = [
    ...
    'rest_framework',
]

Serializer

# blog/serializers.py
from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ['id', 'title', 'content', 'author', 'created_at']

Function-Based View

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET', 'POST'])
def post_list(request):
    if request.method == 'GET':
        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)
        return Response(serializer.data)
    
    elif request.method == 'POST':
        serializer = PostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)

Class-Based View

from rest_framework import generics
from .models import Post
from .serializers import PostSerializer

class PostListCreate(generics.ListCreateAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

class PostRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

URL Patterns

from django.urls import path
from .views import PostListCreate, PostRetrieveUpdateDestroy

urlpatterns = [
    path('api/posts/', PostListCreate.as_view()),
    path('api/posts/<int:pk>/', PostRetrieveUpdateDestroy.as_view()),
]

Mini Practice

  1. Install and configure DRF
  2. Create a serializer
  3. Build API views
  4. Test API endpoints

Up Next

Continue with REST API — REST API design patterns.

Related Topics

Frequently Asked Questions about REST Framework

What is REST Framework in Django?

REST Framework is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn REST Framework?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn REST Framework.

Why is REST Framework important in Django?

REST Framework is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.