RESTful API

HTTP protocol, principle of distributed system architecture (CAP), principle of operating system. . .

References:

Follow Github to learn RESTful HTTP API design

A convention for a RESTful API interface

RESTful API Design Best Practices

Zhihu: How to explain RESTful API in plain language?

 

1. The origin of REST

The full name: REST, the full name is Resource Representational State Transfer, that is: resources are transferred in some form in the network . ——The so-called state transfer can refer to the detailed explanation of the protocol in the book "HTTP Authoritative Guide", but I won't go into details here!

Emergence: REST was first mentioned in a paper published by Dr. Roy Fielding, who also participated in the design of the HTTP protocol. Paper address: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm

Definition: Simply put, REST is a system architecture design style (not a standard), an application-layer solution for distributed systems.

Background: In the early web pages, the front and back were combined, such as PHP, JSP, etc. With the rapid development of mobile terminals and the application of distributed architecture in recent years, various clients emerge in an endless stream. At this time, a unified mechanism is needed to provide services for front-end and back-end communication.

     RESTful API is a relatively mature set of application API design theory.

Purpose: Further decoupling between Client and Server.

Application: The most classic is the github API.

 

Second, the characteristics and advantages of RESTful

1. Client-Server : The server that provides the service and the client that uses the service are separated and decoupled;

   Advantages: Improve the convenience of the client (simple operation)

        Simplified servers improve scalability (high performance, low cost)

        Allows client-server grouping optimizations without affecting each other

2. Stateless : Each request from a client must contain all the information required by the server to process the request (uniqueness of request information);

   Pros: Increased visibility (each request can be considered individually)

        Improved reliability (easier failover)

        Improved scalability (reduced server resource usage)

3. Cachable : The server must let the client know whether the request can be cached? If possible, the client can reuse the previous request information to send the request;

   Advantage: reduce the number of interactive connections

        Reduce the network delay of the connection process

4. Layered System : Allows the middle layer (proxy, gateway, etc.) between the server and the client to respond to the client's request instead of the server, and the client does not need to care about things other than the components it interacts with ;

   Advantages: Improve the scalability of the system

        Simplified system complexity

5. Uniform Interface : The method of communication between the client and the server must be unified. (Example: GET,POST,PUT.DELETE)

   Pros: Improved visibility of interactions

        Encourage individual optimization and improvement of components

6. Support on-demand code (Code-On-Demand, optional) : The server can provide some codes or scripts and execute them in the client's operating environment.

   Pros: Improved scalability

 

3. Outline Design Method

1. Agreement

The communication protocol between the API and the Client always uses the HTTPS protocol.

PS: The use of the HTTPS protocol has little to do with the RESTful API itself, but it is very important to increase the security of the website, especially if the public API is provided, then HTTPS is more important for a long time.

2. Domain name

You should try to deploy the API under a dedicated domain name, such as:

 https://api.github.com 

If the API changes greatly, you can design the API as a subdomain, such as:

 https://example.com/api/v1 

3. Versioning

In general, the API should be put into the URL, such as:

 https://example.com/api/v1 

It is also possible to put the version number in the HTTP header, but this is not as convenient and intuitive as putting it in the URL.

4. Path (Endpoint)

In the protocol, each URL represents the storage address of a resource, so the URL cannot have verbs, but only nouns, and nouns should generally correspond to the table fields of the database, and the nouns in the API should be plural. E.g:

/users/:username/repos
/users/:org/repos
/repos/:owner/:repo
/repos/:owner/:repo/tags
/repos/:owner/:repo/branches/:branch

PS: According to RFC3986, URLs are case-sensitive, so try to use lowercase letters for naming!

5. Method

With the URL design of resources, all operations on resources are specified using HTTP methods. Common methods are (corresponding SQL commands in parentheses):

Green describe
HEAD(SELECT) Get only the header information of a resource
GET(SELECT) Access to resources
POST(CREATE) Create a resource
PATCH(UPDATE) Update some attributes of the resource (rarely used, generally use POST instead)
PUT(UPDATE) To update the resource, the client needs to provide all the properties of the newly created resource
DELETE(DELETE) delete resource

for example:

GET /user: list all users POST /user: create a new user PATCH /user/ID: update the information of a specified user DELETE /user/ID: delete all users

6. Data filtering (Filtering)

If the amount of data is too large, it is impossible for the server to return all the data to the user. The API should provide parameters (such as Query) to filter the returned results. for example:

?limit=10: Specify the number of returned records
?offset=10: specifies the starting position of the returned record
?page=2&per_page=100: Specify the number of pages and the number of records per page
?sortby=name&order=asc: Specifies which property to sort the returned results by and the sort order
?state=close: Specify filter conditions

7. Status code

In the composition of HTTP packets, one field is very important: status code. It describes the general situation of the request, whether it was processed normally, what errors occurred, etc. The status codes are all three digits, roughly divided into several intervals:

Status code description 2XX The request is processed normally and 3XX redirection is returned, and the requested resource location has changed 4XX The request sent by the client is wrong 5XX The error on the server side

status code describe
2XX The request is processed normally and returned
3XX Redirect, the requested resource location changes
4XX The request sent by the client is incorrect
5XX Server side error

Regarding the status code, you can go to my previous blog HTTP status code or refer to other materials for a specific introduction, but I won't go into details here.

8. Error handling

If there is an error, a clear error message should be given in the format of a key-value pair through the message field in the response body.

The most basic idea should be: provide accurate error information as much as possible, such as data format is not correct, a field is missing... instead of saying "request error" directly.

9、Hypermedia API

The design of Restful API is best done by Hypermedia: that is, it provides links to related resources in the returned results, and connects to other API methods, so that users do not need to check documents to know what to do next.

The advantage of this is that the user can get the address that the subsequent operation needs to access according to the returned result.

10. Authentication

Generally speaking, it's bad practice to give anyone free access to a public API, authentication and authorization are two things:

Authentication: Determining that the user is who he claims to be, such as providing an account's password. Otherwise, it is very dangerous for anyone to pretend to be another identity (such as another user or administrator);

Authorization: Ensuring that the user has permission to perform specific operations on the requested resource. For example, a user's private information can only be accessed by himself, and cannot be seen by others; some special operations can only be performed by administrators, and other users have read-only permissions.

If the verification is not passed, the 401 Unauthorized status code needs to be returned, and the specific error information is explained in the body; for resource operations that are not authorized to access, the 403 Forbidden status code needs to be returned, as well as detailed error information.

PS : Github API returns 404 Not Found for resource operations that some users are not authorized to access, the purpose is to prevent the leakage of private resources (for example, hackers can automatically test the user's private resources, and returning 403 is equivalent to telling the hacker that the user has these private resources).

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325948341&siteId=291194637