RESTful learning summary

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 (the Read)
POST: New (the Create)
PUT: Update (Update)
PATCH: Update (Update), usually part of the update
DELETE: Delete (Delete)
according to the HTTP specification, verbs are capitalized.
Covering 1.2 verbs
that some clients can only use these two methods GET and POST. 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
object is the URL API, it is the subject of the role of HTTP verbs. 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 URL complex
since it is a noun URL, 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), there should obviously be plural.
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
client requests each terminal, 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: information
2xx: successful operation
3xx: Redirection
4xx: Client Error
5xx: Server Error
This category contains a total of five 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.
The GET: 200 is the OK
the POST: 201 the Created
the PUT: 200 is the OK
the PATCH: 200 is the OK
the DELETE: 204 No the Content
code above, POST returns 201 status code indicating that generates new resources; 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), since they can be returned by the application level, the browser will jump directly, it may not be level API consider 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 state code
4xx Client Error status code indicates, are the following categories.
400 Bad Request: the server does not understand the client's request, without making any treatment.
401 Unauthorized: user does not provide authentication credentials, or not authenticated.
403 Forbidden: the user is authenticated, but does not have the required permissions to access the resource.
404 Not Found: the requested resource does not exist or is unavailable.
405 Method Not Allowed: the user has authenticated, but the HTTP method used is not within his purview.
410 Gone: the requested resource from the address transfer, are no longer available.
415 Unsupported Media Type: The client requested the return format is not supported. For example, API only returns JSON format, but the client asked to return XML format.
422 Unprocessable Entity: client upload attachments can not handle, resulting in the request fails.
429 Too Many Requests: Client number of requests exceeds the limit.
2.5 5xx status codes
5xx server error status code indicates. 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: client request is valid, the accident occurred when the server process.
503 Service Unavailable: The server was unable to process the request, generally used for site maintenance status.
Third, the server responds with
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 a 200 status code, the error message on the data inside the body, 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 provides links to
the user may not know the API, 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" }
]}
}

四、参考链接
RESTful API Design: 13 Best Practices to Make Your Users Happy, by Florimond Manca
API design, by MicroSoft Azure

Guess you like

Origin www.cnblogs.com/xiaohouye/p/11140133.html