The Web application is divided into two parts, front end and back end. The current trend is the emergence of the front-end equipment (mobile phones, tablets, desktop computers, other special equipment ...). )。
Therefore, there must be a unified mechanism to facilitate the communication of different front-end devices to the backend. This led to the popularity of API architecture, and even the "API first" design idea. RESTful API is currently a relatively mature set of Internet Application API design theory. I've written an understanding of the restful architecture and explored how to understand the concept.
Today, I will introduce the design details of the RESTful API and explore how to design a reasonable and usable API. My main reference is this article, principles of good RESTful API Design.
First, the agreement
The API communicates with the user protocol, always using the HTTPS protocol.
Second, the domain name
The API should be deployed under a dedicated domain name whenever possible.
https://api.example.com
If you determine that the API is simple, there is no further extension, consider placing it under the primary domain name.
https://example.org/api/
Third, version (Versioning)
The version number of the API should be placed in the URL.
https://api.example.com/v1/
Another option is to place the version number in the HTTP header information, but not as convenient and intuitive as placing the URL.
Iv. Path (Endpoint)
The path is also called the "End point" (endpoint), which represents the specific URL of the API.
In a restful architecture, each URL represents a resource (resource), so there can be no verbs in the URL, only nouns, and nouns often correspond to the table names in the database. In general, the tables in the database are "collections" (collection) of the same record, so nouns in the API should also use complex numbers.
For example, there is an API that provides information about zoos, as well as information about various animals and employees, and its path should be designed as follows.
- Https://api.example.com/v1/zoos
- Https://api.example.com/v1/animals
- Https://api.example.com/v1/employees
V. HTTP verbs
For the specific operation type of the resource, it is represented by an HTTP verb.
The usual HTTP verbs have the following five (the corresponding SQL command in parentheses).
- GET (SELECT): Remove resources from the server (one or more items).
- POST (Create): Creates a new resource on the server.
- PUT (UPDATE): Updates the resource on the server (the client provides a full resource after the change).
- PATCH (UPDATE): Updates the resource on the server (the client provides changed properties).
- Delete: Deletes a resource from the server.
There are also two infrequently used HTTP verbs.
- HEAD: Gets the metadata for the resource.
- OPTIONS: Gets information about which properties of a resource are available to the client to change.
Here are some examples.
- Get/zoos: List all Zoos
- Post/zoos: Create a new zoo
- GET/ZOOS/ID: Get information about a given zoo
- PUT/ZOOS/ID: Update information for a designated zoo (all information about the zoo)
- PATCH/ZOOS/ID: Update information for a given zoo (some information about the zoo)
- DELETE/ZOOS/ID: Delete a zoo
- Get/zoos/id/animals: List all animals in a designated zoo
- DELETE/ZOOS/ID/ANIMALS/ID: Delete a designated animal from a designated zoo
Vi. filtering information (Filtering)
If the number of records is large, the server will not be able to return them to the user. The API should provide parameters to filter the returned results.
The following are some common parameters.
- ? limit=10: Specifies the number of records returned
- OFFSET=10: Specifies the start position of the returned record.
- ? SORTBY=NAME&ORDER=ASC: Specifies which property The returned result is sorted by, and the sort order.
- ? Animal_type_id=1: Specifying Filter criteria
The design of the parameter allows redundancy, which allows the API path and URL parameters to be duplicated occasionally. For example, the meaning of Get/zoo/id/animals and Get/animals?zoo_id=id is the same.
State code (status Codes)
The status code and prompt information returned by the server to the user is usually the following (the HTTP verb corresponding to the status code in square brackets).
- $ OK-[GET]: The server successfully returns the data requested by the user, the operation is idempotent (idempotent).
- 201 CREATED-[Post/put/patch]: User new or modified data succeeded.
- 204 NO CONTENT-[delete]: User deleted data successfully.
- INVALID request-[Post/put/patch]: The user has made an error, the server does not make a new or modified data operation, the operation is idempotent.
- 404 Not FOUND-[*]: The user makes a request against a nonexistent record, the server does not operate, the operation is idempotent.
- $ INTERNAL Server Error-[*]: The server is having errors and the user will not be able to determine if the request was successful.
See here for a complete list of status codes.
Viii. error handling (handling)
If the status code is 4xx, you should return an error message to the user. In general, error is used as the key name in the returned information, and error information is used as the key value.
{ error: "Invalid API key"}
Ix. Return of results
For different operations, the results returned by the server to the user should conform to the following specifications.
- Get/collection: Returns a list of resource objects (arrays)
- Get/collection/resource: Returns a single Resource object
- Post/collection: Returns the newly generated resource object
- Put/collection/resource: Returns the full resource object
- Patch/collection/resource: Returns the full resource object
- Delete/collection/resource: Returns an empty document
X. hypermedia API
The RESTful API is best done by hypermedia, which provides links to the returned results, connecting to other API methods, so that users do not look up documents and know what to do next.
For example, when a user makes a request to the root directory of api.example.com, a document is obtained.
{"link": { "rel": "collection https://www.example.com/zoos", "href": "https://api.example.com/zoos", "title": "List of zoos", "type": "application/vnd.yourformat+json"}}
The code above indicates that there is a link property in the document, and the user reads this property and knows what API to call next. Rel represents the relationship between this API and the current URL (collection relationship, and gives the collection URL), the href represents the path to the API, title represents the API's caption, and type represents the return type.
The design of the Hypermedia API is known as Hateoas. The GitHub API is the design that accesses api.github.com to get a list of URLs for all available APIs.
{ "current_user_url": "https://api.github.com/user", "authorizations_url": "https://api.github.com/authorizations", // ...}
As you can see from the above, if you want to get information about the current user, you should go to the api.github.com/user and get the results below.
{ "message": "Requires authentication", "documentation_url": "https://developer.github.com/v3"}
The above code indicates that the server gives the prompt information and the URL of the document.
Xi. Other
(1) The identity authentication of the API should use the OAuth 2.0 framework.
(2) The data format returned by the server should use JSON as much as possible to avoid using XML.
REST API first Knowledge and design