You have to work really hard to look effortless!
Wechat search public number [long Coding road], together From Zero To Hero!
preface
Several API interfaces were designed in the requirement development, and the group leader said that my design was not standard (manual dog head), so I had to learn a wave that weekend to avoid being ridiculed next time.
Introduction to the
In the program development of mainstream companies, in order to improve the speed of program development iteration, the front end is basically separated from the front end architecture, and the front end includes web pages, App, small programs and so on. Therefore, there must be a unified specification to constrain the communication of the front end and the back end. RESTful API is a relatively mature API design theory at present.
To understand RESTful, you need to understand REST. REST, developed by Roy T. Fielding in his doctoral thesis in 2000, is an abbreviation of the phrase REpresentational State Transfer, which translates as “REpresentational State Transfer” but omits the subject — “Resource” — With the addition of a subject is “resource presentation layer state transition”. You can read every word. You don’t know what it means when you put it together?
-
Resource
The so-called resource is an entity on the Internet. Uniform Resource Identifier (URI) is a Uniform Resource Identifier (URI). A resource can be a piece of text, a picture, an audio clip, or a service.
-
Representation
“Resource” is a kind of information entity, which can have many forms of external expression. We call a resource’s Representation of a Representation its’ Representation ‘. An article, for example, can be rendered in XML, JSON, or HTML.
-
State Transfer
Visiting a website represents an interactive process between the client and the server. In this process, data and state changes are inevitably involved. The Internet communication protocol, HTTP, is a stateless protocol, meaning that all state is stored on the server side. Therefore, if the client wants to operate the server, it must somehow make a State Transfer happen on the server side. And this transformation is built on top of the presentation layer, so it is “presentation layer state transformation”.
Since we introduced the basic concepts of REST above, the design of a service REST specification can be called RESTful. Let’s take a look at the design specifications for RESTful apis.
agreement
Protocol is the most basic design. It represents the communication specification of the front and back ends. At this stage, HTTPs should be used.
The domain name
The root entry point of an API should be kept as simple as possible. Here are two common examples:
- Api.example.com/ * (Under Subdomain name)
- example.com/api/* (under main domain)
Domain names should be considered extensible, and if it is uncertain whether the API will be extended later, it should be placed under a subdomain to maintain some flexibility.
The path
The path, also known as the endpoint, represents the specific address of the API. During path design, observe the following conventions:
- Naming must be complete
lowercase
- The resource name must be
noun
“And must beThe plural form
- If you want to use a hyphen, it is recommended to use ‘-‘ rather than ‘_’, ‘_’ may be partially obscured or completely hidden in some browsers or screens
- Easy to read
Names have to be all lowercase and legible and can be understood as prescription. so why do names have to be nouns and plural? This is because in RESTful, the subject is a resource, and the resource must be a noun, not a verb. Second, a resource usually corresponds to a table in the database. A table is a collection of entities, so it needs to be plural.
Here are some counterexamples:
- api.example.com/getUser
- api.example.com/addUser
Here are some examples:
- api.example.com/zoos
- Api.example.com/zoos/animal…
HTTP verbs
There are HTTP verbs for how to manipulate resources. Common verbs include the following five (SQL commands in parentheses) :
- GET (SELECT) : Fetch resources (one or more items) from the server
- POST (CREATE) : Creates a resource on the server
- PUT (UPDATE) : Updates the resource on the server (the client provides the full resource after the change)
- PATCH (UPDATE) : Updates resources on the server (client provides changed properties)
- DELETE (DELETE) : deletes resources from the server
Example:
HTTP verbs | The path | describe |
---|---|---|
GET | /zoos | Get all zoo information |
POST | /zoos | Build a new zoo |
GET | /zoos/ID | Get information about a specified zoo |
PUT | /zoos/ID | Update information for a specified zoo (the front end provides full information about the zoo) |
PATCH | /zoos/ID | Update information for a specific zoo (provides information about changes to that zoo) |
DELETE | /zoos/ID | Delete a zoo |
GET | /zoos/ID/animals | Get information about all the animals in a zoo |
filter
If there is a large amount of data, the server cannot send all the data back to the front end. Therefore, the front end needs to provide some parameters for filtering, paging display, sorting, etc. The following are some common parameters:
- ? Limit =10: Specifies the number of records to return
- ? Offset =10: Specifies the start of the return record.
- ? Page =2&per_page=100: Specifies the number of pages and the number of records per page.
- ? Sortby = name&ORDER = ASC: Specifies by which attribute the return results are sorted, and in what order.
- ? Animal_type_id =1: Specifies a filter condition
HATEOAS
HATEOAS stands for Hypermedia As The Engine Of Application State, literally meaning “Hypermedia is The Engine Of Application State”. The principle is that the client-server interaction is completely provided dynamically by the API, and the client does not need to know how to interact with the server in advance. That is, links are provided in the return results to other API methods so that the user knows what to do next without looking up the documentation.
For example, to handle the relationship between an order and a customer, you can include links in the presentation of an order that specify actions that an ordering customer can perform (view customer information, view order information, delete an order, and so on). Rel represents the relationship between the API and the current url, href represents the path to the API, title represents the title of the API, type represents the return type, and Action represents the supported action type.
{
"orderID":3."productID":2."quantity":4."orderValue":16.60."links":[
{
"rel":"customer"."href":"https://adventure-works.com/customers/3"."action":"GET"."title":"get customer info"."types": ["text/xml"."application/json"] {},"rel":"self"."href":"https://adventure-works.com/orders/3"."action":"GET"."title":"get order info"."types": ["text/xml"."application/json"]]}}Copy the code
Github’s API is designed to do just that. A visit to api.github.com yields a list of all available apis.
{
"current_user_url": "https://api.github.com/user"."emojis_url": "https://api.github.com/emojis"."events_url": "https://api.github.com/events". }Copy the code
Version control
It is highly unlikely that the API will remain static, as new resources may be added and the underlying data structure may change as business requirements change. As you update an API to provide new functionality, you need to consider the impact on users already using the API, so you need to maintain forward compatibility, which leads to version control. The main version control methods are as follows:
- URI Version Management
Add a version number to the URI of each resource every time you modify a Web API or change the schema of a resource. Previously existing URIs should continue to run as before and return resources that match the original schema.
api.example.com/v1/*
api.example.com/v2/*
Copy the code
The versioning mechanism of this approach is very simple, but as the API is iterated over many times, the server needs to support multiple versions of routing, increasing the maintenance cost. This scenario also adds complexity to the HATEOAS implementation, since all links need to include the version number in their URI.
- Query string version control
Instead of providing multiple URIs, you specify the version by appending a query string, such as https://adventure-works.com/customers/3?version=2. If the version parameter is omitted by older client applications, it should default to a meaningful value (for example, 1).
This approach has semantic advantages (that is, the same resource is always retrieved from the same URI), but it relies on code to process the request to parse the query string and send back the appropriate HTTP response. This approach, like the URI versioning mechanism, adds complexity to the implementation of HATEOAS.
- Customize request headers for version control
Customize versioning options in the headers of the request.
GET https://adventure-works.com/customers/3 HTTP / 1.1
Custom-Header: api-version=1
Copy the code
- Accept header for version control
When a client application sends an HTTP GET request to a Web server, the Accept header can dictate the format of the content it can process. Typically, the Accept header is used by the client to specify that the body of the response should be XML, JSON, or some other processable format. However, we can also specify the header as the version of the resource required by the client.
GET https://adventure-works.com/customers/3 HTTP / 1.1
Accept: application/vnd.adventure-works.v1+json
Copy the code
Above example will Accept header is specified for application/VND. Adventure – works. V1 + json. The vnd.adventure-works.v1 element indicates to the Web server that it should return the version v1 of the resource, and the JSON element specifies that the response body should be in JSON format.
This approach is arguably the purest version control mechanism and is a natural fit for HATEOAS, which can include MIME types of associated data in resource links.
In the real world, apis are never completely stable. Therefore, how to manage this change is very important. For most apis, it is acceptable to agree on a partial version control policy, then document the API in detail and phase it out.
Server response
The API response needs to comply with the HTTP design specification and select the appropriate status code to return. You may have seen interfaces that always return a status code of 200 and then use the code field in the return body to distinguish whether the request was successful or not. This is not in compliance with the specification, which means that the status code is useless.
HTTP / 1.1 200 ok
Content-Type: application/json
Server: example.com
{
"code": - 1."msg": "This activity does not exist.",}Copy the code
Second, when an error occurs, error information needs to be returned, and the common way to return is to put it in the return body.
HTTP / 1.1 401 Unauthorized
Server: Nginx / 1.11.9Content-Type: application/json
Transfer-Encoding: chunked
Cache-Control: no-cache, private
Date: Sun, 24 Jun 2018 10:02:59 GMT
Connection: keep-alive
{"error_code":40100."message":"Unauthorized"}
Copy the code
Status code
The HTTP status code consists of three decimal digits. The first decimal digit defines the type of the status code. There are five types of HTTP status codes:
classification | describe |
---|---|
1xx | Message, the server receives the request and requires the requester to proceed with the operation |
2xx | Success, the operation is received and processed successfully |
3xx | Redirect, requiring further action to complete the request |
4xx | Client error, request contains syntax error or request cannot be completed |
5xx | Server error. The server encountered an error while processing the request |
The API does not require 1XX status codes, so let’s focus on a few other common types of status codes:
- 2 xx status code
Status code | English names | describe |
---|---|---|
200 | OK | The request succeeded, usually for GET and POST requests |
201 | Created | The request succeeds and new resources are created for POST, PUT, and PATCH requests. For example, add user, modify user information, etc. Meanwhile, in the return body, we can return all information data of the entity after creation, or we can not return relevant information. |
202 | Accepted | The request was accepted but not completed and will be processed in the future, usually for asynchronous operations |
204 | No Content | The status code indicates that the response entity does not contain any data. This status code is returned when the DELETE operation is performed |
- 3 xx status code
The API does not use 301 status codes (permanent redirection) and 302 status codes (temporary redirection, 307), because they can be returned by the application level and the browser will jump directly to them, and the API level can ignore both cases.
The 3XX status code used by the API is 303 See Other, which refers to another URL. It is a “temporary redirect” in the same sense as 302 and 307, except that 302 and 307 are used for GET requests, while 303 is used for POST, PUT, and DELETE requests. After receiving the 303, the browser does not automatically jump, but lets the user decide what to do next.
Here’s an example.
HTTP/1.1 303 See Other Location: / API/Orders /12345Copy the code
- 4 xx status code
Status code | English names | describe |
---|---|---|
400 | Bad Request | Client request syntax error, server cannot understand |
401 | Unauthorized | Indicates that the user has no permissions (wrong token, username, password) |
403 | Forbidden | Without permission to access the request, the server receives the request but refuses service |
404 | Not Found | The server cannot find the resource based on the client’s request (e.g. path does not exist) |
405 | Method Not Allowed | Methods requested by the client are not supported by the server, for example, using the POST method to request an interface that only supports the GET method |
406 | Not Acceptable | The format of the user GET request is not available (e.g., the user requests JSON format, but only XML format) |
408 | Request Time-out | The client request timed out. Procedure |
410 | Gone | The resource requested by the client GET does not exist. 410 differs from 404 in that if a resource previously had a 410 code that is now permanently deleted, the site designer can specify a new location for the resource through the 301 code |
415 | Unsupported Media Type | It usually indicates that the server does not support the data format specified in the content-type header of the client request. For example, put XML data into an API that only accepts JSON format and send it to the server |
429 | Too Many Requests | The number of client requests exceeds the upper limit. Procedure |
- 5 xx status code
5XX status code Indicates a server error. In general, the API does not reveal server details to the user, so only two status codes are sufficient.
Status code | English names | describe |
---|---|---|
500 | Internal Server Error | Client request valid, server processing an accident |
503 | Service Unavailable | The server is unable to process the request, generally used for website maintenance status |
other
- API authentication should use the OAuth 2.0 framework
- The data format returned by the server should be JSON rather than XML
reference
www.ruanyifeng.com/blog/2011/0…
www.ruanyifeng.com/blog/2014/0…
zhuanlan.zhihu.com/p/68103094
Segmentfault.com/a/119000001…
Docs.microsoft.com/zh-cn/azure…
conclusion
In this article, we looked at the basic concepts and design specifications of RESTful apis, based on which you can tailor your work to your team.
More and more
Personal blog: lifelmy.github. IO /
Wechat official account: Long Coding road