Menu

Django REST Framework

Introduction

Django REST Framework (DRF) is a powerful toolkit for building Web APIs. It provides serializers, viewsets, authentication, and a browsable API out of the box.

Getting started

# Install: pip install djangorestframework

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

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

# views.py
from rest_framework import viewsets
from .models import Post
from .serializers import PostSerializer

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

# urls.py
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('posts', PostViewSet)

urlpatterns = router.urls

Assignment

  1. Install Django REST Framework and create an API for your blog.
  2. Add authentication to your API endpoints.
  3. Test your API using the browsable API and tools like Postman or curl.

Support me!

I am a software engineer giving back to the community - my name is Musila Peter. Join me in empowering learners around the globe by supporting SaneGenius!