0
0
Djangoframework~5 mins

Why DRF matters for APIs in Django

Choose your learning style9 modes available
Introduction

DRF helps you build APIs faster and easier. It handles common tasks so you can focus on your app.

You want to create a web API to share data with mobile apps.
You need to convert your Django models into JSON for other programs.
You want to add user authentication to your API quickly.
You want to handle requests and responses in a clean way.
You want to avoid writing repetitive code for API features.
Syntax
Django
from rest_framework import serializers, viewsets

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

DRF uses serializers to convert data between Python and JSON.

ViewSets group common API actions like list, create, update, and delete.

Examples
This example shows a simple serializer for data validation without a model.
Django
from rest_framework import serializers

class SimpleSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=100)
    age = serializers.IntegerField()
This example shows a basic ViewSet that returns a simple message.
Django
from rest_framework import viewsets
from rest_framework.response import Response

class SimpleViewSet(viewsets.ViewSet):
    def list(self, request):
        return Response({'message': 'Hello API'})
Sample Program

This example shows a complete setup for a simple API to manage books. You can list, add, update, or delete books through the API.

Django
from django.db import models
from rest_framework import serializers, viewsets, routers
from django.urls import path, include
from django.contrib import admin

# Model
class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)

# Serializer
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'title', 'author']

# ViewSet
class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

# Router
router = routers.DefaultRouter()
router.register(r'books', BookViewSet)

# URL patterns
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include(router.urls)),
]

# Explanation:
# This code creates a Book model, a serializer to convert it to JSON,
# and a ViewSet to handle API requests. The router sets up URLs automatically.
OutputSuccess
Important Notes

DRF saves time by handling many API details for you.

It supports authentication, permissions, and pagination out of the box.

Learning DRF helps you build professional APIs with less effort.

Summary

DRF makes building APIs easier and faster.

It uses serializers and viewsets to organize code cleanly.

DRF handles common API tasks so you can focus on your app logic.