Django RESTful Framework "second article" RESTful API

Source: Internet
Author: User
Tags representational state transfer

I. What is restful
    • Rest is not technology-related, it represents a software architecture style, rest is the abbreviation for representational state transfer, and Chinese translates as " representational states transfer "
    • Rest looks at the entire network from the resource's perspective, which identifies the resources distributed across a node in the network through URLs, and the client application uses URLs to obtain representations of the resources, resulting in these applications transforming state
    • All data, whether obtained through the network or the operational database, is a resource that treats all data as resources as the most essential attribute of rest differences and other architectural styles.
    • For the resource-oriented architectural style of rest, a new architectural concept is proposed, namely: resource-Oriented architecture (Roa:resource oriented Architecture)
      • As a resource for anything on the internet, he thinks a URL is a resource such as: http://www.xxx.com/get_user/
Two. Understand what an API is

1. What is an API?

A: The API is the interface that provides the URL. The interface has two uses:

    • -Providing services to others
    • -Front and back end separation, one write Vue, one write back end, they are all through the AJAX request
Third, RESTful API design

The Web application is divided into two parts, front end and back end. The current trend is the emergence of the front-end equipment (mobile phones, tablets, desktop computers, other special equipment ...). )。

Therefore, there must be a unified mechanism to facilitate the communication of different front-end devices to the backend. This led to the popularity of API architecture, and even the "API first" design idea. RESTful API is currently a relatively mature set of Internet Application API design theory.

So let's start with a quick look.

1. Agreement

The API communicates with the user protocol, always using the HTTPS protocol.

2. Domain Name

There are two ways of

Method One: Try to deploy the API in a dedicated domain name (there will be cross-domain issues)

Https://api.example.com

Mode two: If you determine the API is simple, there will be no further expansion, you can consider the main domain name.

https://example.org/api/

3. Version (Versioning)

The version number of the API should be placed in the URL.

https://api.example.com/v1/

Another option is to place the version number in the HTTP header information, but not as convenient and intuitive as placing the URL. GitHub uses this approach.

4. Path (Endpoint)

The path is also called the "End point" (endpoint), which represents the specific URL of the API.

In a restful architecture, each URL represents a resource (resource), so there can be no verbs in the URL, only nouns, and nouns often correspond to the table names in the database. In general, the tables in the database are "collections" (collection) of the same record, so nouns in the API should also use complex numbers.

For example, there is an API that provides information about zoos, as well as information about various animals and employees, and its path should be designed as follows.

Https://api.example.com/v1/zooshttps://api.example.com/v1/animalshttps://api.example.com/v1/employees

5. HTTP verbs

For the specific operation type of the resource, it is represented by an HTTP verb.

The usual HTTP verbs have the following five (the corresponding SQL command in parentheses).

GET (SELECT): Remove resources from the server (one or more items). That is, get the data post (create): Create a new resource on the server. Add data put (update): Updates the resource on the server (the client provides the full resource after the change). That is, update the data patch (UPDATE): Updates the resource on the server (the client provides the changed properties). Update data Delete (delete): Deletes resources from the server  . That is, delete the data

There are also two infrequently used HTTP verbs.

HEAD: Gets the metadata for the resource. OPTIONS: Gets information about which properties of a resource are available to the client to change.

Here are some examples:

Get/zoos: List all zoos Post/zoos: Create a new Zoo GET/ZOOS/ID: Get information about a designated Zoo PUT/ZOOS/ID: update information for a given zoo (all information about the zoo) patch/zoos/ ID: Update information for a specified zoo (providing some information about the zoo) delete/zoos/id: Delete a zoo get/zoos/id/animals: List all animals in a designated zoo delete/zoos/id/animals/ ID: Delete a designated animal from a designated zoo

6. Filtering information (Filtering)

If the number of records is large, the server will not be able to return them to the user. The API should provide parameters to filter the returned results.

The following are some common parameters.

LIMIT=10: Specify the number of records to return? OFFSET=10: Specifies the start position of the returned record. PAGE=2&PER_PAGE=100: Specify the number of pages, and how many records per page. sortby=name&order= ASC: Specifies which attribute the returned result is sorted by, and the sort order. Animal_type_id=1: Specify filter criteria

The design of the parameter allows redundancy, which allows the API path and URL parameters to be duplicated occasionally. For example, the meaning of Get/zoo/id/animals and Get/animals?zoo_id=id is the same.

7. Status code (state codes)

The status code and prompt information returned by the server to the user is usually the following (the HTTP verb corresponding to the status code in square brackets).

$ OK-[GET]: The server successfully returns the data requested by the user, the operation is idempotent (idempotent). 201 CREATED-[Post/put/patch]: User new or modified data succeeded. 202 Accepted-[*]: Indicates that a request has entered the background queue (asynchronous task) 204 NO CONTENT-[delete]: The user deleted the data successfully. INVALID request-[Post/put/patch]: The user has made an error, the server does not make a new or modified data operation, the operation is idempotent. 401 Unauthorized-[*]: Indicates that the user does not have permissions (token, user name, password error). 403 Forbidden-[*] indicates that the user is authorized (as opposed to a 401 error), but access is forbidden. 404 Not FOUND-[*]: The user makes a request against a nonexistent record, the server does not operate, the operation is idempotent. 406 Not acceptable-[GET]: User requested format is not available (such as user request JSON format, but only XML format). 410 Gone-[get]: The resource requested by the user is permanently deleted and will no longer be available. 422 unprocesable Entity-[Post/put/patch] A validation error occurs when an object is created. $ INTERNAL Server Error-[*]: The server is having errors and the user will not be able to determine if the request was successful.

See here for a complete list of status codes.

8. Error handling (handling)

If the status code is 4xx, you should return an error message to the user. In general, error is used as the key name in the returned information, and error information is used as the key value.

{    error: "Invalid API Key"}

9. Return results

For different operations, the results returned by the server to the user should conform to the following specifications

Get/collection: Returns a list (array) of resource objects Get/collection/resource: Returns a single Resource object post/collection: Returns the newly generated resource object put/collection/ Resource: Returns the full resource object Patch/collection/resource: Returns the full resource object Delete/collection/resource: Returns an empty document

10. Hypermedia API Hyper-Media API

The RESTful API is best done by hypermedia, which provides links to the returned results, connecting to other API methods, so that users do not look up documents and know what to do next.

For example, when a user makes a request to the root directory of api.example.com, a document is obtained.

{"link": {  "rel":   "collection Https://www.example.com/zoos",  #表示这个API与当前网址的关系 (collection relationship, And give the collection URL)  "href":  "Https://api.example.com/zoos",  #API路径  "title": "List of Zoos",  # API title  "type":  "Application/vnd.yourformat+json"  #返回类型}}

The design of the Hypermedia API is known as Hateoas. The GitHub API is the design that accesses api.github.com to get a list of URLs for all available APIs.

{  "Current_user_url": "Https://api.github.com/user",  "Authorizations_url": "https://api.github.com/ Authorizations ",  //...}

As you can see from the above, if you want to get information about the current user, you should go to the api.github.com/user and get the results below.

{  "message": "Requires Authentication",  "Documentation_url": "Https://developer.github.com/v3"}

Iv. implementation of the API based on Django

Way One: FBV mode:

Global URL
From Django.contrib import adminfrom django.conf.urls import URL, includefrom app01 import viewsfrom app02 import Viewsurl patterns = [    url (' admin/', Admin.site.urls),    # path (' hosts/', views. Hostview.as_view ()),    url (' app02/', include (' App02.urls '))]

  

App02/url
From APP02 import viewsfrom django.conf.urls Import urlurlpatterns = [    url (' ^users/', views.users),    url (' ^user/ (\d+) ', views.user),    url (' ^users/', views. Usersview.as_view ()),    url (' ^user/', views. Userview.as_view ()),]

  

Views
From django.shortcuts import render,httpresponse# Create your views here.import jsondef users (Request):    response = {' Code ': +, ' data ': None}  #code用来表示状态, e.g. 1000 for success, 1001 for    response[' data ' = [        {' name ': ' Haiyan ', ' age ': 22 },        {' name ': ' Haidong ', ' Age ': ten},        {' name ': ' Haixiyu ', ' age ': one},    ]    return HttpResponse (Json.dumps ( Response))  #返回多条数据def User (REQUEST,PK):    if Request.method = = ' GET ':        return HttpResponse (json.dumps ({' Name ': ' Haiyan ', ' age ': one}))  #返回一条数据    elif Request.method = = ' POST ':        return HttpResponse (json.dumps ({' Code ': 1111}))  #返回一条数据    elif Request.method = = ' PUT ':        pass    elif Request.method = = ' DELETE ':        Pass

  

Way two: CBV mode

App02/urls
From APP02 import viewsfrom django.conf.urls Import urlurlpatterns = [    url (' ^users/'), views. Usersview.as_view ()),    url (' ^user/', views. Userview.as_view ()),]

  

Views
From django.views import Viewclass Usersview (View):    def get (self,request):        response = {' Code ': +, ' data ': None}        response[' data ' = [            {' name ': ' Haiyan ', ' age ': ' $ ',            {' name ': ' Haidong ', ' Age ': ten},            {' name ': ' Haixiyu ', ' age ': one},        ]        return HttpResponse (json.dumps (response), stutas=200) class Userview (View):    def Get (SELF,REQUEST,PK):        return HttpResponse (json.dumps ({' name ': ' Haiyan ', ' age ': one}))  #返回一条数据    def Post (SELF,REQUEST,PK):        return HttpResponse (json.dumps ({' Code ': 1111})  #返回一条数据    def put (self, REQUEST,PK):        pass    def Delete (SELF,REQUEST,PK):        Pass

  

Django-based API many functions need our own development, this time djangorestframework provides us with convenience, directly based on it to return data, in short, the principle is the same, that is, to an interface is the URL, Ask the front-end person to request this URL to fetch the data and display it on the page. This also achieves the effect of front-end separation. Let's take a look at the Django Rest framework-based framework implementation

Implementation based on the Django Rest framework Framework

1, custom certification rules, see links

Class Myauthtication (basicauthentication):    def authenticate (self, request):        token = Request.query_ Params.get (' token ')  #注意是没有GET的, use Query_params to indicate        if token = = ' Zxxzzxzc ':            return (' uuuuuu ', ' AFSDSGDF ') # Return User,auth        Raise Apiexception (' Authentication error ') class Userview (Apiview):    authentication_classes = [Myauthtication,]    def get (Self,request,*args,**kwargs):        print (Request.user)        print (Request.auth)        return Response (' User list ')

2, application: Mainly to do token verification URL As_view inside called the Dispatch method.

There can be two ways of

Local use

urls.py
From APP01 import viewsfrom django.conf.urls Import urlurlpatterns = [    # Django Rest framework    URL (' ^hosts/', view S.hostview.as_view ()),    URL (r ' ^auth/', views. Authview.as_view ()),]

  

views.py
From django.shortcuts import render,httpresponse# Create your views here.from rest_framework.views import Apiviewfrom Res T_framework.views Import requestfrom rest_framework.authentication import Sessionauthenticationfrom rest_ Framework.authentication import baseauthentication, basicauthenticationfrom rest_framework.parsers Import Jsonparserfrom rest_framework.negotiation Import defaultcontentnegotiationfrom rest_framework.exceptions Import Apiexceptionfrom APP01 Import modelsfrom rest_framework.response Import response #友好的显示返回结果class Authview (apiview): #a Uth login page does not require authentication, can be set authentication_classes = [] #登录页面不需要认证 def get (self,request): "' Receive username and password:p Aram Request:: return: ' ret = {' Code ': +, ' msg ': None} user = Request.query_params.get (' Use Rname ') pwd = request.query_params.get (' password ') print (user,pwd) obj = models. UserInfo.objects.filter (USERNAME=USER,PASSWORD=PWD). First () print (obj) if Not obj:ret[' code ' = 1001 ret[' msg '] = ' username or password error ' return Response (ret) #创建随机字 Character string import time import hashlib CTime = Time.time () key = '%s|%s '% (user,ctime) m = Hashli B.MD5 () m.update (Key.encode (' utf-8 ')) token = M.hexdigest () #保存数据 obj.token = token obj . Save () ret[' token '] = token return Response (ret) class Hostview (Apiview): Def dispatch (self, request, *ar    GS, **kwargs): Return super (). Dispatch (Request, *args, **kwargs) # authentication_classes = [Myauthtication] def get (Self,request,*args,**kwargs): Print (Request.user, ' dddddddddddffffff ') print (Request.auth, ' dddddddddd ') #原来的request, Django.core.handlers.wsgi.WSGIRequest #现在的request, Rest_framework.request.Request # PR int (request) authentication_classes = [Sessionauthentication,baseauthentication] # print (self.authentication _classes) # [<class' Rest_framework.authentication.SessionAuthentication ';, # <class ' Rest_f Ramework.authentication.BasicAuthentication ';] return HttpResponse (' Get Request response content ') def post (Self,request,*args, **kwargs): Pass # Try: # try: # current_page = Request. Post.get ("page") # # current_page = Int (current_page) # int ("ASD") # EXCEP T valueerror as E: # print (e) # raise #如果有raise说明自己处理不了了, give it to one of the following to capture the # except except        Ion as E: # print ("OK") return HttpResponse (' Post request Response content ') def put (self, request, *args, **kwargs): return HttpResponse (' response content for put request ')

  

Global use

Settings
#注册认证类REST_FRAMEWORK = {    ' unauthenticated_user ': None,    ' Unauthenticated_token ': none,  #将匿名用户设置为None    "default_authentication_classes": [        "App01.utils.MyAuthentication",    ],}

  

Global validation
From  rest_framework.authentication import baseauthenticationfrom rest_framework.exceptions Import Apiexceptionfrom app02 Import Modelsclass myauthentication (baseauthentication):    def authenticate (self, request):        token=request.query_params.get (' token ')        print (token)        obj=models. UserInfo.objects.filter (Token=token). First ()        print (obj)        if obj:            return (obj.username,obj)        Raise  apiexception (' No validation ')

  

Note: Rest_framewor is an app that needs to be activated first in settings.

Django RESTful Framework "second article" RESTful API

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.