Based on Django RESTframework design Restful API

Lead

  Questions about RESTful encountered a lot in recent interviews, there have been before a certain understanding, but there is no systematic analyzed. So now combined with Django RESTframework to deepen the understanding of RESTful while combing some of the knowledge of this process.

What is RESTful?

 This problem is most likely to think, we must first analyze the problem, the Internet will be other articles talked about the REST (Representational State Transfer), Chinese translation: "representational state transfer", then the vernacular point is representational state transfer of resources . At first, we see here have a big head, then we take a look at the point where the knowledge learned more critical needs.

Resources (resources)

 Resource here refers to each entity on the network, and each entity has a corresponding URI (Uniform Resource Identifier), if you need to access the resources, you can access it through the URI can be.

Representation (presentation layer)

 Simply the manifestation of the resource, such as images, HTML, text, and so on.

State Transfer (state conversion)

  The client can operate the resource through GET, POST, PUT, DELETE HTTP verb.

summary

  REST to look from the perspective of the whole network resources, and then distributed to a node in the network identified by URI, and the client and server is some delivery resources presentation layer, and the client through the HTTP verbs, server resources operation, to achieve "state conversion expression." (Expression: the client requests a resource, and by the server to get the resource)
 that satisfies the above constraints and principles of these applications or design is RESTful. In other words RESTful is an architecture of norms and constraints.

RESTful API

API terms of design, RESTful is now a common design specifications, commonly used to design Web data interface. Here to talk about the details of the design from the Internet a general summary of several RESTful API.

URI design

1, verb + object

 The client uses "Verb + object" structure operating a server resource, the verb refers to the HTTP verb, object refers to the resource. HTTP verbs server resource corresponding to the operation:

  • GET (SELECT): Remove the resource from the server (one or more).
  • POST (CREATE): a new resource on the server.
  • PUT (UPDATE): update the resource (after the complete resources provided by the client to change) in the server.
  • PATCH (UPDATE): Updating Resource (provided by the client to change the properties) in the server.
  • DELETE (DELETE): Delete the resource from the server.

2, the object must be a noun

 Since the object in the API URI, is the subject of the role of HTTP verbs, nouns should be, not a verb.

3, 复数 URI

 For URI recommend the use of the plural

3, avoid multi-level URI

status code

Every client request, the server response is given, and the response HTTP status codes comprises two parts and data.
HTTP status code meaning:

  1. 1xx: information
  2. 2xx: Successful operation
  3. 3xx: Redirection
  4. 4xx: Client Error
  5. 5xx: Server Error

Server response

1, do not return to plain text

 API returns data format should not be a plain text, should be a JSON object, this is consistent with a structured process. The same server response HTTP Content-Type header of the same property to be set to application / json.

2, when an error occurs, do not return a 200 status code

 In the event of an error, it should not return a 200 status code, then an error message on the data volume, because this would result in the need to know the complete body analysis data operation fails.

Django RestFramework

Django RestFramework is based on building a RESTful style in line with the Django Web api, and also with its own test page, easy to test their API, so for the "separation of the front and rear end" in terms of development model is very appropriate.

On the front and rear end of the separation

 Front and rear ends of a rear separating finger is only necessary to provide a data interface, no longer renders the template, and the distal end only require data presentation. This has many advantages:

  • Decoupling front and rear ends, the multiplexed interfaces, the amount of reducing development
  • Carry out their duties, before and after the end of the synchronous development, improving efficiency, will be a good interface specification
  • More useful for debugging, testing and operation and maintenance

Django RestFramework Profile

Rest Framework basic components:

  • APIView
  • Parser component: parsing the data request, the request is parsed in accordance with different title
  • Serialization component: similar to the Django Form, desired data can be obtained in the form of custom action by
  • View class (a mixin)
  • Certified Components
  • Permissions components
  • Frequency components
  • Paging component
  • Responsive assembly
  • url registrar

Process flow

 About Django view function, can be based on FBV mode can also be based on CBV mode :

  • FBV Mode: Django route map table associates url and view function
  • CBV mode: and CBV model is defined in views.py view classes, view functions in the view class, such as (get, post, put, delete ) , etc.
     Django RESTFramework is based CBV mode , when the Django a http request arrives, the method first performs middleware, and then performing the matching route.

Based on Django RESTframework design Restful API

 When the route match, performs custom class as_view () method, if there is no parent class will call as_view () method, then call to the dispatch () method for processing different REQUEST request, perform different methods. (Designed to Django CBV mode processing flow of this process, as well as some source of knowledge)

Django RESTframework use

Project Configuration

Install Django restframework:

pip install djangorestframework

Based on Django RESTframework design Restful API

New projects, new applications, modify settings.py

django-admin startproject Crawl
cd Crawl
python manage.py startapp music

settings.py (rest_framework will add to INSTALLED_APPS)

Based on Django RESTframework design Restful API

(The rest of the configuration modify the database, modify the language, time zone, not one listed)
project file tree:

Based on Django RESTframework design Restful API

Project Database Design

设计一个有关于存储歌曲的详细信息表(music/models.py):

from django.db import models

class Music(models.Model):
    music_author = models.CharField(max_length=50, verbose_name='歌唱者')
    music_name = models.CharField(max_length=100, verbose_name='歌曲名')
    music_album = models.CharField(max_length=100, verbose_name='专辑')
    music_time = models.CharField(max_length=10, verbose_name='歌曲时间')
    music_type = models.CharField(
        max_length=100, null=True, verbose_name='歌曲类型', default=None)
    music_lyrics = models.CharField(
        max_length=100, blank=True, verbose_name='作词者')
    music_arranger = models.CharField(
        max_length=100, blank=True, verbose_name='作曲者')

同步数据库:

python manage.py makemigrations
python manage.py migrate

Serializers

创建一个序列化Serialier类,提供序列化和反序列化的途径,使之可以转化为如json的表现形式,类似于Django的Form表单的原理。在music目录下,创建serializers.py:

from rest_framework import serializers
from music.models import *

class MusicSerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = Music

Views.py和Urls.py

通过前面提到的CBV模式,设计视图处理函数和路由映射:
Crawl/urls.py

from django.contrib import admin
from django.urls import path, include
import music

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('music.urls')),
]

music/urls.py

from django.urls import path
from music.views import *

urlpatterns = [
        path('', MusicList.as_view()),
        path('<int:pk>/', MusicDetail.as_view()),
        ]

music/views.py

from django.shortcuts import render
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from music.models import *
from music.serializers import MusicSerializer

# Create your views here.

class MusicList(APIView):
    def get(self, request):
        queryset = Music.objects.all()
        ret = MusicSerializer(queryset, many=True)
        return Response(ret.data)

    def post(self, request):
        music = MusicSerializer(data=request.data)

        if music.is_valid():
            music.save()
            return Response(music.data)
        else:
            return Response(music.errors)

class MusicDetail(generics.RetrieveAPIView):
    queryset = Music.objects.all()
    serializer_class = MusicSerializer

代码详解:

 代码比较简单,主要就是继承restframework框架的通用视图函数generics,或者APIView。如果先省事,建议generics,因为提供的通用视图可以允许你快速构建与数据相关的API视图,当然如果觉得通用视图不适合自己的API需求,可以使用APIView类。
(在这里两种方式都用到了,可以对比他们的区别)

测试结果

模拟请求API接口(GET、POST请求)
Based on Django RESTframework design Restful API

Based on Django RESTframework design Restful API
Based on Django RESTframework design Restful API

自带的测试页面:
Based on Django RESTframework design Restful API

总结

刚开始接触到RESTful方面的知识还是非常懵的,对网上很多文章感觉讲的也不是很全面,所以索性总结一下,然后接触到RESTFramework框架也发现到了很多在Django方面不熟悉的地方,如CBV模式,以及工作的原理,有些都牵扯到框架内的源码,也是从网上一些优秀的文章一点点慢慢了解到,之后对Django RESTframework相关知识也会继续总结学习,下面是我在网上参考的一些文章,有兴趣的可以了解一下。

参考链接:

https://www.cnblogs.com/renpingsheng/p/9531649.html
https://www.cnblogs.com/renpingsheng/p/9534984.html#FeedBack
https://www.jianshu.com/p/08a998f74ac7

Guess you like

Origin blog.51cto.com/mbb97/2431272