Django RESTful API design guide, djangorestful
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. I have previously written an article "Understanding RESTful architecture" to explore how to understand this concept.
Today, I will introduce the design details of RESTful APIs and discuss how to design a set of reasonable and useful APIs. My main reference is Principles of good RESTful API Design.
1. Protocol
The communication protocol between APIs and users always uses HTTPs.
2. Domain Name
Try to deploy the API under a dedicated domain name.
Https://api.example.com
If you confirm that the API is simple and will not be further expanded, you can consider placing it under the primary domain name.
Https://example.org/api/
3. 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.
4. Path (Endpoint)
The path is also called "endpoint", indicating the specific api url.
In a RESTful architecture, each website address represents a resource. Therefore, there cannot be any verb in the website, but only nouns, And 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/zoos
Https://api.example.com/v1/animals
Https://api.example.com/v1/employees
5. HTTP verb
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
POST/zoos: Create a 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: lists 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.
? Sortby = name & order = asc: Specify the attribute in which the returned results are sorted and the sorting 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.
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 ..
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.
500 internal server error-[*]: if an ERROR occurs on the SERVER, you cannot determine whether the request is successful.
For a complete list of status codes, see here.
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": "Collections https://www.example.com/zoos ",
"Href": "https://api.example.com/zoos ",
"Title": "List of zoos ",
"Type": "application/vnd. yourformat + json"
}}
The code above indicates that there is a link attribute in the document. When you read this attribute, you will know what API to call next. Rel indicates the relationship between the API and the current URL (collection relationship, and the URL of the collection is given). href indicates the API path, title indicates the API title, and type indicates the return type.
Hypermedia APIs are designed as HATEOAS. The Github API is designed like this. Accessing api.github.com will get a list of all available API URLs.
{
"Current_user_url": "https://api.github.com/user ",
"Authorizations_url": "https://api.github.com/authorizations ",
//...
}
We can see from the above that if you want to obtain the information of the current user, you should access api.github.com/user, and then you will get the following result.
{
"Message": "Requires authentication ",
"Documentation_url": "https://developer.github.com/v3"
}
The code above indicates that the server provides the prompt information and the URL of the document.
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 using XML