Build a RESTful Web API with Django REST framework

This article was first published from "MOOC" (www.imooc.com). If you want to know more about IT dry goods and hot news in the programmer circle, please pay attention to "MOOC" and "MOOC Official Account"!

Author: ExcellentDavid | MOOC Lecturer


This time, we take the teacher-student management system as an example to lead you to build a set of framework Web API. "If a worker wants to do a good job, he must first sharpen his tools." We use the most popular Django REST framework as a tool to quickly implement this set of APIs.

Installing Django REST framework requires the following dependencies:

  • Python (3.5, 3.6, 3.7, 3.8)
  • Django (1.11, 2.0, 2.1, 2.2, 3.0)

The Django REST framework is provided as a Django extension application, so we can directly use the existing Django environment without recreating it. (If there is no Django environment, you need to create an environment to install Django first)

1. Install Django REST framework

pip install django 
pip install djangorestframework

 django installation process:

 django-rest-framework installation process:

2. Create projects and applications

django-admin startproject ProjectDemo
django-admin startapp AppDemo

After the project and application are created, the directory structure is shown in the figure below:

3. Register rest_framework application

Django REST framework can be regarded as an application of Django. Before using it, it needs to be registered in INSTALLED_APPS of settings.py .

# settings.py

INSTALLED_APPS = [
    ...
    'rest_framework',
]

After completing the above operations, you can use Django REST framework to develop Restful Web API. Next, we will take the student management system as an example to show you how Django REST framework can efficiently develop REST API.

4. Create, migrate models, and add data

Building a data model is the basis for building a Restful Web API. Building a model is equivalent to building a database structure without the need for cumbersome SQL language. Another advantage is that even if you switch between different database engines (mysql, SQL Server, Oracle, etc.), you don't need to rebuild. Below we build a student information table, including student name, student age and student number.

# models.py

from django.db import models

class StudentsInfo(models.Model):
		'''
		学生信息模型
		'''
    # 以下为学生信息表中的各个字段,CharField、IntegerField声明了字段类型分别为字符串类型和整型,max_length规定了字段最大长度,verbose_name相当于给字段取了一个别名,将来在管理页面会显示这个别名,否则显示字段名。例如,如果设置了verbose_name,那么在管理页面中,s_name字段将一“学生姓名”显示出来,如果没有设置verbose_name,则直接显示“s_name”。verbose_name只是方便用户以后的使用,设置与否不影响内部数据的存储。
    s_name = models.CharField(max_length=8, verbose_name='学生姓名')
    s_age = models.IntegerField(verbose_name='学生年龄')
    s_number = models.CharField(max_length=16, verbose_name='学号')

Run the command in the terminal to migrate the model

python manage.py makemigrations
python migrate

Add demo data to the database, here we can use the Database tool that comes with PyCharm to complete. Since we are using sqlite3 as the database, when adding data, double-click the db.sqlite3 file in the file directory on the left, and then double-click the data table (AppDemo_studentsmodel) to be operated in the Database tool on the right.

In the opened data table, fill in the data to be filled:

5. Create a serializer

Usually, an API includes operations in two directions, one is that the client requests data from the server, and the other is that the client submits data to the server. When the client requests data from the server, the server retrieves the corresponding data from the database, serializes it through the serializer, and then passes it to the client by the view; when the client submits data to the server, the data is processed by the view layer, and then the serializer Deserialized, and finally stored in the database.

In the Restful Web API, the serializer is equivalent to the data docking bridge between the client and the database. It can serialize the data in the server into a data form that the client can parse. On the contrary, it can also convert the data provided by the client Data, deserialized into a data form that meets the requirements of the database. Next, we create a new serializers.py in the AppDemo application to save the serializer of the application.

Create a StudentsSerializer for serializing and deserializing student information:

# serializers.py

from rest_framework import serializers
from AppDemo.models import StudentsModel

class StudentsSerializer(serializers.ModelSerializer):

    class Meta:
        # 对StudentsModel进行序列化
        model = StudentsModel
        # __all__表示对 StudentsModel 中所有字段序列化进行序列化
        fields = '__all__'
  • model : Indicates that the data fields processed by the serializer are generated from the reference of the model class StudentsModel;
  • fields : Indicates which fields in the model class the serializer contains, ' all 'indicates that all fields are included.

5. Write the view

In Restful Web API, the view plays the role of data processor . For example, the client needs to obtain the average score of each subject after a final exam of a student, but only the scores of each subject are stored in the database. At this time, the view needs to process the data, calculate the average according to the scores of each subject, and then return to the client. Since there is no need to process the data in this case, the implementation of the view is relatively simple. Create a view BookInfoViewSet in views.py of the booktest application , which is a collection of views.

# views.py

from rest_framework import viewsets
from AppDemo.models import StudentsModel
from AppDemo.serializers import StudentsSerializer

class StudentsViewSet(viewsets.ModelViewSet):

    queryset = StudentsModel.objects.all()
    # 使用上一步创建的StudentsSerializer对模型进行序列化
    serializer_class = StudentsSerializer

  • queryset indicates the query set used by the view set when querying data;
  • serializer_class specifies the serializer to use for this view when serializing or deserializing.

6. Define routes

Routing is used to define different path addresses corresponding to different interfaces of RESTful Web API. In this case, we want to obtain the information of the students. According to the design specifications introduced in Section 3, the address should be designed as: http://www.demo.com/api/students . Define routing information in urls.py of ProjectDemo .

from django.contrib import admin
from django.urls import path, include
from rest_framework import routers

from AppDemo.views import StudentsViewSet

router = routers.DefaultRouter() # 创建路由器
router.register(r'students', StudentsViewSet)	# 在路由器中注册视图集路由地址

urlpatterns = [
  	# 拼接路由路径
    path('api/', include(router.urls)),
]

8. Run the tests

Run the current program in the terminal (same as running Django):

python manage.py runserver

At this point, our RESTful Web API has been built. Since we are testing locally, the API domain name part uses the local machine address. Enter http://127.0.0.1:8000/api in the browser address bar to see all interface connections in the current project.

Click the link http://127.0.0.1:8000/api/students/ to go to the student information interface and get all the student information, as shown in the following figure:

 In the form at the bottom of the page, we can enter student information and click the POST button to add new student information to the student list:

 After clicking the POST button, the following information is returned:

 At this time, click the GET button again, and we find that the student (Xiaobai) added in the previous step has been displayed in all student information.

 Enter the URL 127.0.0.1:8000/api/students/2/ in the browser to access the interface for obtaining a single student information (student with id 2), as shown in the following figure:

 If you need to modify the student's information, you can fill in the information to be modified in the form at the bottom of the page, and you can access the interface for modifying a single student . We modify Xiaohong's age to 20:

 Click PUT to return the following page information, and Xiaohong's age information has been modified at this time:

 Click the DELETE button to access the interface for deleting students :

 Click DELETE to return, and the following page shows that the student Xiaohong with id 2 has been deleted:

9. Summary

This section mainly explains the installation method of Django and Django REST framework, and uses Django REST framework to implement a simple student management system RESTful Web API. So far, a simple API conforming to the RESTful specification has been created.


Welcome to pay attention to the official account of "MOOC". We will always insist on providing high-quality content in the IT circle, sharing dry knowledge, and let's grow together!

This article was originally published on Muke.com, please indicate the source for reprinting, thank you for your cooperation

Guess you like

Origin blog.csdn.net/mukewangguanfang/article/details/130864053