100 RESTful API, 100 restfulapi

Source: Internet
Author: User
Tags representational state transfer

100 RESTful API, 100 restfulapi

Navigate to this article:

  • RESTful
  • RESTful API design
  • Django-based implementation
  • Implementation Based on Django Rest Framework

 

1. RESTful

REST is independent of technology and represents a software architecture style. REST is short for Representational State Transfer"

REST looks at the entire network from the perspective of resources. It identifies the resources of a node distributed in the network by URL, and the client application obtains the resource characterization through URL, obtaining these representations leads to changes to these applications

REST is independent of technology and represents a software architecture style. REST is short for Representational State Transfer"

All data, however, is obtained through the network or operated (add, delete, modify, query) data, is a resource, and all data is regarded as the most essential attribute of the difference between resources and other Architecture styles.

For the Resource-Oriented Architecture Style of REST, someone puts forward a brand new structure concept, namely, Resource-Oriented Architecture (ROA: Resource Oriented Architecture)

 

2. RESTful API design

Network applications are divided into two parts: front-end and back-end. The current development trend is the emergence of front-end devices (mobile phones, tablets, desktops, and other specialized devices ......).

Therefore, a unified mechanism is required to facilitate communication between different front-end devices and backend devices. This leads to the popularity of the API architecture and even the design idea of "API First. RESTful API is a mature API design theory for Internet applications.

An API is an interface that provides a url. The interface has two purposes:

-Provide services to others

-Frontend and backend separation: one write vue and one write backend. They all use ajax requests.

1. Agreement

The communication protocol between APIs and users always uses HTTPs.

2. Domain Name

Https://api.example.com try to deploy the API in a dedicated domain (there will be cross-domain issues) https://example.org/api/ API is very simple

3. Version (Versioning)

Put the API version number into the URL.

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

Another approach is to put the version number in the HTTP header information, but it is better to put the version number in the URL for convenience and intuition. Github adopts this approach.

4. Path (Endpoint)

The path is also called "endpoint", indicating the specific api url.

In a RESTful architecture, each URL represents a resource.TermAnd the nouns used often correspond to the table names in the database. In general, tables in the database are all collections of the same type of records, so the nouns in the API should also use the plural.

For example, if an API provides zoo information and contains information about animals and employees, 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 verb (method)

The specific operation type of a resource is represented by an HTTP verb.

Common HTTP verbs include the following five (corresponding SQL commands in parentheses ).

GET (SELECT): Extracts resources from the server (one or more ). POST (CREATE): CREATE a resource on the server. PUT (UPDATE): UPDATE resources on the server (the client provides the complete resources after the change ). UPDATE: UPDATE resources on the server (the client provides the changed attributes ). DELETE: deletes resources from the server.

There are two other uncommon HTTP verbs.

HEAD: gets metadata of a resource. OPTIONS: obtain information about which attributes of the resource can be changed by the client.

The following are some examples.

GET/zoos: list all zoo posts/zoos: Create a New Zoo GET/zoos/ID: GET the information of a specified zoo PUT/zoos/ID: update the information of a specified zoo (provide all information about the zoo) PATCH/zoos/ID: update the information of a specified zoo (provide some information about the zoo) DELETE/zoos/ID: DELETE a zoo GET/zoos/ID/animals: list all animals in a specified zoo DELETE/zoos/ID/animals/ID: DELETE a specified animal in a specified Zoo

6. Filtering)

If there are many records, the server cannot return them to the user. The API should provide parameters to filter the returned results.

Below are some common parameters.

? Limit = 10: specify the number of returned records? Offset = 10: Specify the start position of the returned record .? Page = 2 & per_page = 100: Specify the page number and the number of records on each page .? Sortby = name & order = asc: Specify the attribute in which the returned results are sorted and their order .? Animal_type_id = 1: Specify the filtering Conditions

The parameter design allows redundancy, that is, the API path and URL parameters can be repeated occasionally. For example, GET/zoo/ID/animals and GET/animals? Zoo_id = ID has the same meaning.

7. Status Codes)

The status code and prompt information returned by the server to the user. Common Information is as follows (the HTTP verb corresponding to the status code is in square brackets ).

200 OK-[GET]: The server successfully returns the data requested by the user. This operation is Idempotent (Idempotent ). 201 CREATED-[POST/PUT/PATCH]: The data is successfully CREATED or modified. 202 Accepted-[*]: indicates that a request has entered the background Queue (asynchronous task) 204 no content-[DELETE]: The user successfully deleted the data. 400 invalid request-[POST/PUT/PATCH]: The user sends a REQUEST with an error. The server does not create or modify data. This operation is idempotent. 401 Unauthorized-[*]: indicates that the user does not have the permission (token, user name, and password are incorrect ). 403 Forbidden-[*] indicates that the user is authorized (as opposed to the 401 error), but the access is Forbidden. 404 not found-[*]: The user sends a request for a non-existent reCord. If the server does NOT perform any operation, the operation is idempotent. 406 Not Acceptable-[GET]: the format of the user request is Not available (for example, the JSON format of the user request, but only the XML format ). 410 Gone-[GET]: Resources requested by the user are permanently deleted and will not be obtained. 422 Unprocesable entity-[POST/PUT/PATCH] A verification error occurs when an object is created. 500 internal server error-[*]: if an ERROR occurs on the SERVER, you cannot determine whether the request is successful.

Full list of status codes see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

8. Error handling)

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

{    error: "Invalid API key"}

9. Returned results

For different operations, the results returned by the server to the user must comply with the following specifications.

GET/collection: returns the list of resource objects (array) GET/collection/resource: returns a single resource object POST/collection: returns the newly generated resource object PUT/collection/resource: returns the complete resource object PATCH/collection/resource: returns the complete resource object DELETE/collection/resource: returns an empty document

10. Hypermedia API

RESTful APIs are best implemented in Hypermedia, that is, links are provided in the returned results and connected to other API methods, so that users do not check documents and know what to do next.

For example, if you send a request to the root directory of api.example.com, you will get such a document.

{"link": {  "rel":   "collection https://www.example.com/zoos",  "href":  "https://api.example.com/zoos",  "title": "List of zoos",  "type":  "application/vnd.yourformat+json"}}

11. Others

1) The OAuth 2.0 Framework should be used for API authentication.

2) the data format returned by the server should be JSON as much as possible to avoid XML.

 

Iii. django-based implementation

1. FBV Mode

Global url

from django.contrib import adminfrom django.conf.urls import url, includeurlpatterns = [    url('admin/', admin.site.urls),    url('api/', include('api.urls'))]

Api. urls

from api import viewsfrom django.conf.urls import urlurlpatterns = [    url('^users/', views.users),    url('^user/(\d+)', views.user),]

Views

From django. shortcuts import render, HttpResponse # Create your views here. import jsondef users (request): response = {'code': 1000, 'data': None} # code indicates the status. For example, 1000 indicates success, 1001 stands for response ['data'] = [{'name': 'haiyan ', 'age': 22}, {'name': 'haidong', 'age ': 10}, {'name': 'haixiyu ', 'age': 11},] return HttpResponse (json. dumps (response) # returns multiple data records def user (request, pk): if request. method = 'get': return HttpResponse (json. dumps ({'name': 'haiyan ', 'age': 11}) # returns an elif request. method = 'post': return HttpResponse (json. dumps ({'code': 1111}) # returns an elif request. method = 'put': pass elif request. method = 'delete': pass

2. CBV Mode

Api. urls

from api 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': 1000, 'data ': none} response ['data'] = [{'name': 'haiyan ', 'age': 22}, {'name': 'haidong', 'age ': 10}, {'name': 'haixiyu ', 'age': 11},] return HttpResponse (json. dumps (response), stutas = 200) class UserView (View): def get (self, request, pk): return HttpResponse (json. dumps ({'name': 'haiyan ', 'age': 11}) # returns a data def post (self, request, pk): return HttpResponse (json. dumps ({'code': 1111}) # returns a data def put (self, request, pk): pass def delete (self, request, pk): pass

Many functions of Apis implemented based on django need to be developed by ourselves. At this time, the Django Rest Framework provides us with convenience.

 

IV. Implementation Based on Django Rest Framework

Url. py

from django.conf.urls import url, includefrom web.views.s1_api import TestView urlpatterns = [    url(r'^test/', TestView.as_view()),]

Views. py

From rest_framework.views import APIViewfrom rest_framework.response import Response class TestView (APIView): def dispatch (self, request, * args, ** kwargs): "after the request arrives, you must execute the dispatch method. The dispatch method triggers get, post, and put methods based on different request methods. Note: The dispatch method in APIView has many features "" return super (). dispatch (request, * args, ** kwargs) def get (self, request, * args, ** kwargs): return Response ('get request, Response content ') def post (self, request, * args, ** kwargs): return Response ('Post request, Response content') def put (self, request, * args, ** kwargs): return Response ('put request, Response content ')

The above is the basic process of the rest framework. An important function is to trigger it in the dispatch of APIView.

Django can be used without the django rest_Framework framework, but it provides some common API functions, such as: (authentication, permission, throttling, with these features, we only need to write a class that has been configured. It can be used as an urban graph and can be configured globally. If you write it yourself, you have to write middleware and decorator to implement it, through the Django rest_Framework framework, the rule has been written, and only the class needs to be written. Only the method can be implemented and the return value can be used.) Some functions are implemented.

 

Related Article

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.