SoFunction
Updated on 2024-11-20

Django Rest Framework framework to build complex API skills in detail

introductory

Definition and Purpose of Django REST Framework

The Django REST Framework, often shortened to DRF, is a powerful and flexible Web API toolkit. Using DRF , developers can quickly build scalable , maintainable RESTful API services . DRF provides a full set of tools and modules , including authentication , permissions , serialization , views , routing , etc. , to help us deal with many common problems in Web development .

The main purpose of the DRF is to make it easy for Django applications to build and manage APIs. in addition, the DRF focuses on the navigability and ease of use of the APIs, allowing developers to access the APIs and interact with them through a web browser.

Django REST framework vs. other frameworks (e.g. Flask)

Although the Django REST framework and other Python web frameworks (such as Flask) share the common goal of helping developers build web applications, they differ in their design philosophy, functionality, and usage scenarios.

  • Design Concept: DRF is a more "heavyweight" framework , provides a complete set of solutions , including models , views , templates , forms , routing , authentication , permissions and so on. Flask is more lightweight and flexible , it only provides the most basic tools , the other features need to install extensions to achieve .
# Django view example
from  import HttpResponse
def hello_world(request):
    return HttpResponse("Hello, World!")

# Flask view example
from flask import Flask
app = Flask(__name__)
@('/')
def hello_world():
    return 'Hello, World!'
  • functionality: DRF provides many built-in features such as authentication, permissions, serialization, deserialization, views, routing, etc. These features have been carefully designed so that developers can focus more on business logic rather than infrastructure. Flask , on the other hand , is more focused on flexibility , it allows developers to choose and customize the desired features .
  • Usage Scenarios: If your project needs to build RESTful APIs quickly, or needs to be tightly integrated with other parts of Django (e.g. ORM, templating system, etc.), then DRF might be a better choice. If you need more flexibility or just need to build a simple web service, then Flask may be more appropriate.

basic part

Django REST framework installation and setup

Before you can start using the Django REST framework, you first need to install and configure the relevant environment. Assuming you already have Python and Django installed, you can use pip to install the DRF:

pip install djangorestframework

Then, therest_frameworkAdd to your Django project'sINSTALLED_APPSConfiguration:

# 

INSTALLED_APPS = [
    ...,
    'rest_framework',
]

With this, we have successfully installed and configured the Django REST framework, and we can start building our first DRF project next.

A basic Django REST framework project build tutorial

In this tutorial, we will create a simple API for managing book information. First, we need to create a new Django app:

python  startapp books

Then, we need to add thebooks app to define our model:

# 

from  import models

class Book():
    title = (max_length=200)
    author = (max_length=100)
    published_date = ()

    def __str__(self):
        return 

Next, we need to define the corresponding Serializer and Viewset:

# 
from rest_framework import serializers
from .models import Book
class BookSerializer():
    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'published_date']
# 
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet():
    queryset = ()
    serializer_class = BookSerializer

Finally, we need to add theAdd the route in the

# 

from  import include, path
from rest_framework.routers import DefaultRouter
from .views import BookViewSet

router = DefaultRouter()
(r'books', BookViewSet)

urlpatterns = [
    path('', include()),
]

Above is the process of building a basic Django REST framework project. In this example, we have created a book information API that can perform CRUD operations.

Basic Components in Django REST Framework: Serializers, Viewsets, Routers

In the above example, we used the three main components of DRF: Serializers, Viewsets, and Routers.Here is a brief description of them:

  • Serializers: Responsible for converting complex data types (e.g. Django model instances) into Python data types that can be rendered into formats such as JSON, XML, and so on. It can also be used to parse data in the above formats and convert them to complex data types.
  • Viewsets: A class for encapsulating view logic. Similar to Django's class view , but provides more REST-related functionality , such as the default GET, POST, PUT, PATCH and DELETE methods .
  • Routers: Responsible for automatically generating URL routes. Similar to Django's URLconf, but with better support for DRF's Viewsets, which can automatically create corresponding routes according to the methods in the Viewset.

In the next sections, we'll dive into how these three components work and how to use them.

Serializers

Serializers play a crucial role in the Django REST framework. They are responsible for converting complex data types, such as Django model instances or complex query sets, so that they can be rendered into a transportable format like JSON or XML. Serializers are also responsible for doing the deserialization work when the data is received, converting the received data to Python data types.

What is Serializer?

Serializers are similar to Django's Form and ModelForm classes, but they contain not only simple data validation features, but also complex type conversion features. They can serialize complex data types (converting to basic Python data types) and also deserialize serialized data (converting to complex data types).

# 

from rest_framework import serializers
from .models import Book

class BookSerializer():
    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'published_date']

In the above example, theBookSerializeris a Serializer, which inherits from the ModelSerializer class and is used to serialize and deserialize Book model instances.

How Serializers Work

When serializing an object, Serializers first convert the object to Python's built-in data types and then convert those data types to a transferable format. When deserializing, Serializers perform the opposite process, first converting the received data to Python's built-in data types and then converting those data types to complex data types.

Here is a simple example demonstrating how to use theBookSerializerPerform serialization and deserialization:

# Serialization with Serializer
book = (id=1)
serializer = BookSerializer(book)
print()
# exports:{'id': 1, 'title': 'Django for Beginners', 'author': 'William S. Vincent', 'published_date': '2022-07-01'}
# Deserialization with Serializer
data = {'title': 'REST API with Django', 'author': 'William S. Vincent', 'published_date': '2023-07-01'}
serializer = BookSerializer(data=data)
if serializer.is_valid():
    book = ()
print(book)
# exports:<Book: REST API with Django>

Examples and Usage of Serializers

The most common usage scenario for Serializers is in views, for serializing and deserializing data processed by the view.

For example, we can use a Serializer in the view to handle a POST request from the client to create a new book:

# 

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Book
from .serializers import BookSerializer

class BookList(APIView):
    def post(self, request):
        serializer = BookSerializer(data=)
        if serializer.is_valid():
            book = ()
            return Response(, status=status.HTTP_201_CREATED)
        return Response(, status=status.HTTP_400_BAD_REQUEST)

In the above example, we used the view's POST method with theBookSerializer, deserializes the received data into Book model instances and saves them to the database.

Serializers are widely used, they can be used not only for basic data validation and conversion, but also for complex scenarios such as dealing with nested data, custom fields, dynamic fields, and so on. After mastering the basic usage, you can further explore various advanced uses of Serializers according to your needs.

ViewSets

In the Django REST framework, ViewSets is an important component that provides a high-level view abstraction that makes it easier to implement API interfaces based on RESTful principles.

What is a ViewSet?

A ViewSet can be thought of as a collection of multiple views. In the Django REST framework, a ViewSet is similar to a Class-Based Views in Django, but it provides more default behavior and a wider range of functionality, such as default implementations of GET, POST, PUT, PATCH, and DELETE operations.

# 

from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer

class BookViewSet():
    queryset = ()
    serializer_class = BookSerializer

In the above example, theBookViewSetIt is a ViewSet that inherits from theModelViewSetClass, forBookThe model implements a full set of CRUD operations.

How ViewSets work

ViewSet works very similar to Django's class views. It maps HTTP methods to the corresponding methods in the ViewSet, for example a GET request will map to thelistorretrievemethod, the POST request is mapped to thecreatemethod, PUT and PATCH requests are mapped to theupdatemethod, the DELETE request is mapped to thedestroyMethods.

Here is a simple example demonstrating how to use theBookViewSetHandles GET and POST requests:

# Use ViewSet to handle GET requests
from rest_framework.test import APIRequestFactory

factory = APIRequestFactory()
request = ('/books/')
response = BookViewSet.as_view({'get': 'list'})(request)
print(response.status_code)
# Output: 200

# Use ViewSet to handle POST requests
request = ('/books/', {'title': 'Django REST Framework', 'author': 'Tom Christie', 'published_date': '2023-07-01'})
response = BookViewSet.as_view({'post': 'create'})(request)
print(response.status_code)
# exports:201

Examples and Usage of ViewSets

The most common usage scenario for ViewSet is in URLconf to create URL routes for API interfaces.

For example, we can use the URLconfBookViewSetto create URL routes for the Book API:

# 

from  import include, path
from rest_framework.routers import DefaultRouter
from .views import BookViewSet

router = DefaultRouter()
(r'books', BookViewSet)

urlpatterns = [
    path('', include()),
]

In the above example, we registered in URLconf theBookViewSet, the Django REST framework automatically creates a new set of rules for theBookViewSetCreate a set of URL routes that correspond to the various operations defined by it.

The use of ViewSet is very flexible , they can not only be used to implement basic CRUD operations , but also can be used to implement complex logic , such as permission control , filtering , paging and so on. After mastering the basic usage, you can further explore various advanced uses of ViewSet according to your needs.

Routers

In the Django REST framework, Routers provide a clean way to create and manage URL configurations for ViewSets. Using Routers, we can quickly create and configure URLs, reducing repetitive work.

What is a Router?

The Router automatically creates URL configurations for view sets, providing a standard set of URL configurations for CRUD operations for each view set.The use of the Router greatly improves development efficiency, eliminating the need to manually create each URL.

The following is a simple example of using a Router:

# 

from  import include, path
from rest_framework.routers import DefaultRouter
from .views import BookViewSet

router = DefaultRouter()
(r'books', BookViewSet)

urlpatterns = [
    path('', include()),
]

In the above example, we created a router using DefaultRouter and then called its register method to register the BookViewSet, which automatically creates a standard set of URL configurations for the BookViewSet.

How a Router Works

When you register a view set with the Router, the Router automatically creates a URL configuration for the view set. This URL configuration corresponds to the methods of the view set, such as list, create, retrieve, update, and destroy.

router = DefaultRouter()
(r'books', BookViewSet)

In the above example, the router creates the following URL configuration for BookViewSet:

  • /books/: Corresponds toBookViewSet (used form a nominal expression)list cap (a poem)create methods that handle GET and POST requests, respectively;
  • /books/{pk}/: Corresponds toBookViewSet (used form a nominal expression)retrieveupdate cap (a poem)destroy methods that handle GET, PUT/PATCH, and DELETE requests, respectively.

Examples and Usage of Router

In the Django REST framework, there are two common types of Routers:DefaultRouter cap (a poem)SimpleRouterDefaultRouter provides a set of routing configurations that include an additional browser interface, while theSimpleRouter then provides a simple set of basic routing configurations.

Router is very flexible, you can register as many view sets as you want, and use different Routers in different Django apps. after mastering the basic usage, you can also delve into how to customize the Router, such as customizing the URL configuration, customizing the name of the URL, and so on.

Permissions and Authentication

Permissions and authentication are a very important part of building an API , they determine whether the user can access your API and what the user can do . Django REST Framework provides a comprehensive set of permissions and authentication system , so that you can easily control the user's access rights .

accreditation

Authentication is the process of determining the identity of a user.Django REST Framework supports a variety of authentication methods, such as SessionAuthentication, TokenAuthentication, BasicAuthentication and so on.

The following is an example of how to use TokenAuthentication in a view:

# 

from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer

class BookViewSet():
    queryset = ()
    serializer_class = BookSerializer
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

In this example, we set the authentication_classes attribute for BookViewSet, specifying the use of TokenAuthentication.When a user requests a BookViewSet, the Django REST Framework checks the request's HTTP header to see if it contains a valid token to identify the user.

scope of one's jurisdiction

Permissions are rules that determine what an authenticated user can do.Django REST Framework provides several ways to manage permissions, such as IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly, and so on.

In the above example, we set the permission_classes attribute for BookViewSet, specifying the use of IsAuthenticated. this means that only authenticated users can access the BookViewSet.

Customized authentication and permissions

In addition to using the authentication and permission management methods provided by the Django REST Framework, you can also customize authentication and permissions. Customizing authentication and permissions gives you more flexibility in controlling user access.

Below is an example of a custom permission class that only allows authors to access their own books:

# 

from rest_framework import permissions

class IsAuthor():
    def has_object_permission(self, request, view, obj):
        return  == 

You can then use this custom permission in the view:

# 

from .permissions import IsAuthor
# Other imports...

class BookViewSet():
    # Other codes...
    permission_classes = [IsAuthenticated, IsAuthor]

In this example, the IsAuthor permission class checks each request and if the requesting user is not the author of the book, the request will be denied.

Testing and Debugging

Testing and debugging is an important step to ensure the quality of the code . Django REST Framework provides a set of tools for testing and debugging the API .

beta (software)

Django REST Framework integrates with Django's testing framework and provides some additional functionality for testing APIs.You can use Django REST Framework's APIClient class to simulate an API request and then inspect the response.

Below is a sample test:

# 

from  import reverse
from rest_framework import status
from rest_framework.test import APITestCase, APIClient
from .models import Book

class BookTests(APITestCase):
    def setUp(self):
         = APIClient()
         = (title='Test Book', author='Test Author')

    def test_get_book(self):
        url = reverse('book-detail', kwargs={'pk': })
        response = (url)
        (response.status_code, status.HTTP_200_OK)
        (['title'], 'Test Book')
        (['author'], 'Test Author')

In this example, we first create an APIClient and a Book instance in the setUp method. Then, in the test_get_book method, we use the APIClient to make a GET request and then examine the status code and data in the response.

adjust components during testing

The Django REST Framework provides a browser interface for debugging the API, which allows you to access the API directly in the browser, view response data, or issue POST, PUT, PATCH, and DELETE requests. The browser interface is very intuitive and is a great tool for debugging the API.

To use the browser interface, you just need to enable it in:

# 

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.',
        'rest_framework.',
        # Other renderers...
    ]
}

In the above setup, we enabled BrowsableAPIRenderer, which will enable the browser interface. You can now access the API in the browser.

Debugging with tools

There are many tools available to help you debug APIs such as Postman, Insomnia, etc. These tools can simulate various HTTP requests, view details of requests and responses, and save and organize API requests. If you need to do complex API debugging, these tools may be helpful.

While testing and debugging may take some time, they are key to ensuring the quality of your code. When writing code, don't forget to write tests and perform debugging.

summarize

At this point, we have provided an in-depth overview of the Django REST Framework. We started off with the basics of the Django REST Framework and then dug into Serializers, ViewSets, and Routers.We also discussed permissions and authentication systems, and how to test and debug.

The Django REST Framework provides many powerful tools that make building complex APIs easy. However, mastering these tools takes time and practice. I hope this article helps you get started on your Django REST Framework journey.

Finally, I want to reiterate some of the key points we discussed in the article:

  • Serializers are used for data serialization and deserialization.
  • ViewSets are classes used to handle view logic.
  • Routers are responsible for URL generation and distribution.
  • The Django REST Framework provides a robust permissions and authentication system.
  • You can use the Django REST Framework's testing tools and debugging interface to test and debug your API.

Above is the Django Rest Framework framework to build complex API skills explained in detail , more about Django Rest Framework to build API information please pay attention to my other related articles !