RESTful API is the most popular design specifications for the design of Web data interface. It's easy to grasp the principle, but the details are not easy to do right.
This article summarizes the design details RESTful, and how to design the API easy to understand and use.
A, URL Design
1.1 verb + object
RESTful core idea is that the client data manipulation instruction is issued "Verb + object" structure.
For example, GET / articles this command, GET is a verb, / articles is the object. The method of HTTP verb is usually five kinds corresponding CRUD operations.
GET: read (Read)
POST: New (Create)
PUT:更新(Update)
PATCH: Update (Update), usually a partial update
DELETE: 删除 (Delete)
According to the HTTP specification, verbs are capitalized.
1.2 verbs cover
Some clients can only use these two methods GET and POST, the server must accept POST simulate the other three methods (PUT, PATCH, DELETE)
At this time, HTTP requests from the client, to add X-HTTP-Method-Override attribute, which tells the server should use a verb, covering the POST method.
POST /api/Person/4 HTTP/1.1 X-HTTP-Method-Override: PUT 复制代码
The above code, X-HTTP-Method-Override this request specifies the method is PUT, instead of POST.
1.3 object must be a noun
The object is the URL API, HTTP is the object of the verb action. It should be a noun, not a verb.
For example, / articles this URL is correct, but the following URL is not a noun, it is wrong.
/ getAllCars
/createNewCar
/deleteAllRedCars
1.4 complex URL
Since the URL is a noun, you should use the plural or singular? This is no uniform requirement, but common operation is to read a collection.
Such as GET / articles (read all the articles), this should be clearly complex.
For the sake of consistency, the proposed use complex URL, such as GET / articles / 2 better than GET / article / 2.
1.5 avoid multi-level URL
Common situation is that resources need to multi-level classification, so it is easy to write multi-level URL, such as access to an author of some articles.
GET /authors/12/categories/2复制代码
This URL is not conducive to expansion, semantics is not clear, often in order for a while, in order to understand the meaning.
Better yet, in addition to the first level, the other levels are used query string expression.
GET /authors/12?categories=2复制代码
Here is another example, query the published article. You may be designed to the following URL.
GET /articles/published复制代码
The query string wording significantly better.
GET /articles?published=true
复制代码
Second, the status code
2.1 Status codes must be precise
Customer end of each request, the server must be given a response. Response HTTP status codes comprises two parts and data.
HTTP status code is a three-digit number, divided into five categories.
1xx
:Related Information
2xx
:Successful operation
3xx
: Redirect
4xx
: Client Error
5xx
:Server Error
It contains a total of five categories of 100 kinds of status codes, covering the vast majority of situations that may be encountered.
Each status code has standard (or agreed) explained that the client simply check the status code, you can determine what happened, so the server should return as accurately as possible the status code.
API does not require 1xx status codes, the following describes four other precise meaning of the status codes.
2.2 2xx status code
200 status code indicates a successful operation, but different methods can be more accurately returned status code.
GET: 200 OK
POST: 201 Created
PUT: 200 OK
PATCH: 200 OK
DELETE: 204 No Content
In the above code, the POST returns 201 status code indicating that a new resource is generated; the DELETE returns the 204 status code indicating that the resource does not exist.
Further, 202 Accepted status code indicates that the server has received the request, but not yet processed, the processing will be further in the future, normally used for asynchronous operation.
Below is an example.
HTTP/1.1 202 Accepted
{
"task": {
"href": "/api/company/job-management/jobs/2130040",
"id": "2130040"
}
}
复制代码
2.3 3xx status code
API less than 301 status code (permanent redirect) 302 and a status (temporary redirection, also the meaning of 307)
Because they can be returned by the application level, the browser will jump directly, API level can not consider these two cases.
3xx status code API used mainly 303 See Other, express reference to another URL.
Meaning it is the same as 302 and 307, are "temporary redirection", except that for the GET request 302 and 307, and 303 for the POST, PUT and DELETE requests.
After receiving 303, the browser will not automatically jump, and let the user decide how to do next.
Below is an example.
HTTP/1.1 303 See Other Location: /api/orders/12345复制代码
2.4 4xx status code
4xx status code indicates a client error, are the following categories:
The Request of Bad 400 : the server does not understand the client's request, without making any treatment
Unauthorized 401 : user does not provide authentication credentials, or not authenticated
Forbidden 403 : the user is authenticated, but does not have the required permissions to access resources
Not Found 404 : The requested resource does not exist, or is not available
Method, Not the Allowed 405 : user has been authenticated, but the HTTP method used is not within his purview
Gone 410 : The requested resources from this address transfer is no longer available
Unsupported Media Type 415 : The client requested the return format is not supported. For example, API only returns JSON format, but the client asked to return XML format
Unprocessable the Entity 422 : client upload attachments can not handle, resulting in the request fails
Too Many Requests 429 : the number of client requests exceed the limit.
2.5 5xx status code
5xx status code indicates that the server error. In general, the API server details will not be disclosed to the user, so long as the two status code is enough.
500 Internal Server Error accident occurred when a client request is valid, the server processes:
Service Unavailable Papers with 503 : The server was unable to process the request, generally used for site maintenance status
Third, the server responds
3.1 Do not return to a pure paper
API returns data format should not be plain text, but rather a JSON object, because it can return to the standard of structured data.
Therefore, the server responds with the Content-Type HTTP header attribute is set to application / json.
When a client requests, it must clearly tell the server can accept JSON format, ACCEPT attribute that is requested HTTP header should be set to application / json.
Below is an example.
GET /orders/2 HTTP/1.1 Accept: application/json 复制代码
3.2 When an error occurs, do not return a 200 status code
One approach is inappropriate, even if an error occurs, it returns the status code 200, the error information is placed inside the body of data, such as the following.
HTTP/1.1 200 OK
Content-Type: application/json
{
"status": "failure",
"data": {
"error": "Expected at least two items in list."
}
}
复制代码
In the above code, after parsing the data body, in order to know the operation failed.
This practice is in fact canceled status code, which is totally undesirable. The correct approach is, to reflect the status code error has occurred, the error specific information in the data returned inside the body.
Below is an example.
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": "Invalid payoad.",
"detail": {
"surname": "This field is required."
}
}
复制代码
3.3 link
API users may not know, URL is how design. One solution is to, in response, are given links to facilitate the next step.
In this case, users just remember a URL, you can find other URL. This method is called HATEOAS.
For example, GitHub's API are api.github.com this domain. To access it, you can get other URL.
{
...
"feeds_url": "https://api.github.com/feeds",
"followers_url": "https://api.github.com/user/followers",
"following_url": "https://api.github.com/user/following{/target}",
"gists_url": "https://api.github.com/gists{/gist_id}",
"hub_url": "https://api.github.com/hub",
...
}复制代码
In response to the above, pick a URL access, you can get another URL. For users, the design does not need to remember URL, simply look up from api.github.com a step by step on it.
HATEOAS format is no specification for the above example, GitHub put them together with other attributes. A better way is to separate links with other attributes.
HTTP/1.1 200 OK
Content-Type: application/json
{
"status": "In progress",
"links": {[
{ "rel":"cancel", "method": "delete", "href":"/api/status/12345" } ,
{ "rel":"edit", "method": "put", "href":"/api/status/12345" }
]}
}复制代码
End
Author: Ruan Yifeng
source:
http://www.ruanyifeng.com/blog/2018/10/restful-api-best-practices.html
This article belongs to the author of all
Long press the map two-dimensional code, civet cats immediate concern [technical] nest
Ali, Jingdong, the US group, beating top technical experts based in bytes
IT people to create a "temperature" technology nest!