Introduction to the

Representational State Transfer, or REST, describes an architecture-style network system. REST refers to a set of architectural constraints and principles. An application or design that satisfies these constraints and principles is RESTful.

Concept:

  • Resources REST is “presentation level state transformation”. It actually omits the subject. The “presentation layer” actually refers to the “presentation layer” of “resources”. So what are resources? It’s a picture, a document, a video, etc. These resources are identified by A URI, meaning that a URI represents a resource.

  • A Representation resource is a Representation of a specific entity, which can be represented in a variety of ways. And the entity to show is the performance layer, such as a TXT text information, he can output into HTML, JSON, XML and other formats, a picture he can JPG, PNG and other ways to show, this is the meaning of the performance layer. A URI identifies a resource, but how do you determine its representation? You should specify Accept and Content-Type fields in the HTTP request header, which describe the presentation layer.

  • State Transfer visiting a website represents an interactive process between the client and the server. In this process, data and state changes are definitely involved. The HTTP protocol is stateless, so these states must be kept on the server side, so if the client wants to notify the server side of changes in data and state, there must be some way to notify it.

URI format specification

A document is a single representation of a resource and can be understood as an object or a record in a database. When requesting a document,

Either the data corresponding to the document is returned, or a link to another resource (document) is returned.

Here are a few examples of urIs based on document definitions:

https://api.example.com/users/will

https://api.example.com/posts/1

https://api.example.com/posts/1/comments/1

Copy the code
  • Collection (Collection)
A collection can be thought of as a container (directory) of resources to which we can add resources (documents). Such as:

https://api.example.com/users

https://api.example.com/posts

https://api.example.com/posts/1/comments

Copy the code
  • Warehouses (Store)
A repository is a repository managed by clients. Clients can add or delete resources to the repository.

Clients can also batch obtain all resources under a repository. External access to resources in the repository does not provide a separate URI.

The exception is the URI when the client creates the resource. Such as:

PUT /users/1234/favorites/posts/1

In the example above we can understand that we add to the repository of a user whose ID is 1234,

A POST resource with ID 1 is added. In plain English: it means that the user collects an article with id 1 as his favorite.

Copy the code
  • Controller (the Controller)
The controller resource model can execute a method that supports input of parameters and return of results. In addition to standard operation:

Some logical operations other than CRUD. The controller (method) generally defines the end of the subURI,

There will be no child resources (controllers). Such as:

Resend the message 245743 to the user

POST /alerts/245743/resend



Publish the article with ID 1

POST /posts/1/publish

Copy the code

Turn actions into resources

Github does this by converting actions into resources that can perform CRUD operations.



For example, "like" a gist, it is increase in the gists/:id/star.

Gists: "Like" the use of PUT /gists/: ID /star,

"Gists" in the DELETE /gists/: ID /star

Alternatively, use POST /gists/: ID /unstar



Another example is Fork, which is also an action, but add forks under gist,

Gists in the gists can perform the action of the user fork.

Copy the code

URI naming conventions

  • Resources of Document type are named with singular nouns (phrases)
  • Resources of the Collection type are named plural nouns (phrases)
  • Resources of the Store type are named with plural nouns (phrases)
  • Controller resources are named with verbs (phrases)
  • Some fields in the URI can be variables that can be replaced as needed in practice
For example, a resource URI might be defined like this:

https://api.example.com/posts/{postId}/comments/{commentId}

PostId,commentId are variables (numbers, strings, etc.).

Copy the code
  • CRUD operations should not be represented in urIs. Operators in the HTTP protocol already map to CRUD.
CRUD stands for Create, Read, Update, delete

For example, delete operations performed using REST specifications would look like this:

DELETE /users/1234



Here are a few examples of errors:

GET /deleteUser? id=1234

GET /deleteUser/1234

DELETE /deleteUser/1234

POST /users/1234/delete

Copy the code

The QUERY field of the URI

In REST,query fields typically complement queries and can also help identify a unique resource. However, as a URI providing query functionality, we should ensure that the result is unique regardless of whether there is a query condition. The data returned by a URI should not be changed (if the resource is not modified). Caching in HTTP may also cache query results.

  • The Query argument can be used as a filter for a Collection or Store resource. For example:
GET /users // Returns a list of all users

GET /users? Role =admin // Returns the list of users with admin permission

GET /search/users? Q ={query}{&page,per_page,sort,order

Copy the code
  • The Query parameter can be used as a pagination flag for a Collection or Store resource list
For a simple list operation, you can design it like this:

GET /users? pageSize=25&pageStartIndex=50

If it is a complex list or query operation, we can design a Collection for resources,

Because complex queries may involve many parameters, you are advised to use Post, for example:

POST /users/search



Related paging information can also be stored in the Link header so that the client can get the next, last, or previous page directly

And so on

Status: 200 OK

Link: <https://api.github.com/resource?page=2>; rel="previous",

<https://api.github.com/resource?page=2>; rel="next",

<https://api.github.com/resource?page=5>; rel="last"

X-RateLimit-Limit: 20

X-RateLimit-Remaining: 19

Copy the code

Use of HTTP request methods

  • The GET method is used to GET resources
  • The PUT method can be used to add/update resources of type Store
  • The PUT method can be used to update all attributes of a resource, passing the values of all attributes even if some values have not changed
  • The PATCH method updates some properties of the resource. Because PATCH is relatively new and the specification is complex, there are few real implementations, and POST is generally used instead
  • The POST method is used to create a resource
  • The POST method can be used to trigger the execution of a Controller type resource
  • The DELETE method is used to DELETE a resource

The use of HTTP response status codes

  • 200 (” OK “) is used for general success returns
  • 200 (” OK “) cannot be used to request error returns
  • 201 (” Created “) Resource is Created
  • 202 (” Accepted “) is a return for asynchronous processing of a Controller control-class resource, indicating only that the request has been received. Processing that takes a long time is usually done asynchronously
  • 204 (” No Content “) This status may appear in PUT, POST, or DELETE requests. It generally indicates that the resource exists, but the message body does not return any status or information related to the resource.
  • The URI of the 301 (” Moved Permanently “) resource has been Moved and needs to be accessed using a new URI
  • 302 (” Found “) is not recommended, this code is replaced by 303/307 in the HTTP1.1 protocol. We currently use of 302 and first HTTP1.0 definition of semantic is discrepancy, should be only under the GET/HEAD method, the client can jump automatically according to the Location to perform, and our current client is basically not judge the original request method, unconditional execute temporary redirect
  • 303 (” See Other “) returns a reference to the URI of a resource address, but does not force the client to obtain the state of the address (to access it)
  • 304 (” Not Modified “) has a similar state to 204. The version of the resource on the server is the same as that of the most recently accessed resource on the client. The resource body is Not returned. Can be used to reduce stress on the server side
  • 307 (” Temporary Redirect “) Currently the URI cannot provide the requested service and is temporarily redirected to another URI. 307 was used in HTTP1.1 to replace 302, which was misused in earlier HTTP1.0
  • 400 (” Bad Request “) is used for the client to return general errors. It can also be used for errors other than 4XX errors. The specific error information can be placed in the body
  • 401 (” Unauthorized “) An authentication error occurred while accessing a resource that requires authentication
  • 403 (” Forbidden “) is generally used when access to non-authenticating resources is Forbidden, for example, when some clients only have access to some apis, but others may be inaccessible, you can give 403 status
  • 404 (” Not Found “) The resource corresponding to the URI cannot be Found
  • 405 (” Method Not Allowed “) HTTP methods are Not supported. For example, some read-only resources may Not support POST or DELETE. However, the 405 response header must declare the method supported by the URI
  • 406 (” Not Acceptable “) The data format type of the resource requested by the client is Not supported, for example, application/ XML is requested by the client, but only Application/JSON is supported on the server
  • 409 (” Conflict “) Resource state Conflict. For example, a client tries to delete a non-empty Store resource
  • 412 (” Precondition Failed “) is used when conditional operations are not fulfilled
  • 415 (Unsupported Media Type) The server cannot support the data Type supported by the customer
  • The 429 (” Too Many Requests “) client sent Too Many Requests in the specified period of time, which can be used when limiting traffic
  • 500 (” Internal Server Error “) An interface Error on the Server. This Error is not related to the client

HTTP Headers

  • Content-type Specifies the data format of the body
  • Content-length Body Indicates the size of the data body. The client can use this identifier to check whether the read data is complete or use the Header to determine whether to download a large data body
  • Last-modified, used in response to the server, is the timestamp of the Last modification of a resource. The client (cache) can use this information to determine whether to retrieve the resource
  • ETag Indicates the version of the resource on the server. The client (cache) can determine whether to obtain the resource again based on this information. Note that if the ETag is randomly generated by the server, multiple hosts may generate different ETags for the same resource
  • Resources of the Store type must support conditional PUT requests
Suppose two clients #1/#2 both submit a PUT request to a Store resource, and the server cannot clearly determine whether to

Insert is still update, so we need to add if-match, if-unmodified-since conditions to the header

To clarify the purpose of this call to the API. Such as:



Client# 1 first sends a request to the server. PUT /objects/2113 if the 2113 resource does not yet exist, the server will

This request is considered an INSERT operation, and when it is done, 201 (" Created ") is returned.



Client# 2 sends the same request to the server again, PUT /objects/2113, because 2113 resources already exist, the server will

Return 409 (" Conflict ")



In order for the client#2 request to succeed, or for us to make it clear that the operation is an update, we must set the

Add some criteria to the header, such as if-match. We need to give the ETag(if-match: ETag) of the resource to table

We want to update the version of the resource. If the server version is the same, either 200 (" OK ") or 204 (" No Content ") will be returned.

If the server finds the specified version inconsistent with the current resource version, 412 (" Precondition Failed ") is returned

Copy the code
  • Location is used in the response header and is usually the resource URI of interest to the client. For example, after successfully creating a resource, we can place the new resource URI in Location. If it is an asynchronous request to create a resource, The interface can respond to 202 (” Accepted “) while giving the client an address for an asynchronous status query
  • Cache-control, Expires, Date The interface response performance can be improved through the caching mechanism, and the client can also be prohibited from caching interface requests based on actual requirements. In the case of REST interfaces where real time requirements are not high, we can specify a small cache time with max-age, which is beneficial to both the client and the server. In general, we only use caching for GET methods that return 200, but in some cases we can also cache for 3xx or 4xx to prevent the load from incorrect access.
  • We can customize headers for communication between the client and the server, but we cannot change the nature of the HTTP method. Keep your custom headers simple and don’t supplement them with information from the body.

API address and version

It’s a good idea to specify the version of the API in the URL. If the API changes a lot, you can design the API as a subdomain, such as api.github.com/v3. You can also simply put the version… Example.com/api/v1. Alternatively, put the version number in the HTTP header.

Current limiting rate limit

If the number of accesses is not controlled, apis can be abused or even attacked by DDos. Limiting traffic according to users’ different identities can prevent these situations and reduce the pressure on the server.

After limiting a user’s request, there is a way to tell the user about its request usage. The Github API uses three related headers:

  • X-ratelimit-limit: indicates the maximum number of requests that a user can send in an hour
  • X-ratelimit-remaining: indicates the number of Remaining available requests in the current time window
  • X-ratelimit-rest: When the time window is reset, the number of requests available at this point in time will change to the value of x-ratelimit-limit

For requests that exceed traffic, you can return the 429 Too Many Requests status code with an error message.

Reference documentation

  • Cizixs.com/2016/12/12/…
  • Wangwei. Info/about – rest -…
  • www.ruanyifeng.com/blog/2011/0…
  • www.ruanyifeng.com/blog/2014/0…
  • zh.wikipedia.org/wiki/REST
  • developer.github.com/v3
  • Novoland. Making. IO/BE AE E8% % % % E…