Network application, divided into front-end and back-end two parts. The current development trend is the endless emergence of front-end devices (mobile phones, tablets, desktops, other dedicated devices……) .
Therefore, there must be a unified mechanism to facilitate communication between different front-end devices and back-end devices. This led to the popularity of API architectures and even the idea of “API First” design. RESTful API is a relatively mature set of API design theory of Internet applications. I’ve written an article on Understanding RESTful Architecture that explores how to understand this concept.
Today, I’m going to go into the details of RESTful API design and explore how to design a reasonable and user-friendly API. I mainly refer to two articles (1,2).
One, the agreement
The API always uses HTTPs to communicate with users.
Second, the domain name
The API should be deployed under a private domain as much as possible.
https://api.example.com Copy the code
If you determine that the API is simple and will not be extended further, consider placing it under the main domain.
https://example.org/api/ Copy the code
Iii. Versioning
You should put the VERSION number of the API in the URL.
https://api.example.com/v1/ Copy the code
The alternative is to put the version number in the HTTP header, but it’s not as convenient and intuitive as putting it in the URL. Github takes this approach.
4. Path (Endpoint)
The path, also known as the endpoint, represents the specific URL of the API.
In a RESTful architecture, each url represents a resource, so there can be no verbs in the url, only nouns, and the nouns usually correspond to the table names in the database. Generally speaking, tables in a database are “collections” of the same records, so nouns in apis should also be plural.
For example, if there is an API that provides information about zoos, as well as information about various animals and employees, its path should look like this.
- https://api.example.com/v1/zoos
- https://api.example.com/v1/animals
- https://api.example.com/v1/employees
HTTP verbs
The specific types of operations on resources are represented by HTTP verbs.
There are five common HTTP verbs (the corresponding SQL commands are in parentheses).
- GET (SELECT) : Retrieves one or more resources 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 (the client provides the changed properties).
- DELETE (DELETE) : deletes resources from the server.
There are also two less commonly used HTTP verbs.
- HEAD: obtains the metadata of the resource.
- OPTIONS: Get information about which properties of the resource can be changed by the client.
Here are some examples.
- GET /zoos: List all zoos
- POST/upshot: A new zoo
- GET /zoos/ID: GET information about a specified zoo
- PUT /zoos/ID: Update information for a specified zoo (provides full information about that zoo)
- PATCH /zoos/ID: Update information for a specified zoo (provides partial information for that zoo)
- DELETE /zoos/ID: Deletes a zoo
- GET /zoos/ID/animals: Lists all the animals in a given zoo
- DELETE /zoos/ID/animals/ID: Deletes a specified animal for a specified zoo
Vi. Information Filtering
If there are many records, the server cannot return them all to the user. The API should provide parameters that filter the return results.
Here 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
The parameters are designed to allow for redundancy, that is, occasional duplication of API path and URL parameters. For example, GET /zoo/ID/animals versus GET /animals? Zoo_id =ID has the same meanings.
7. Status Codes
The status code and prompt message returned by the server to the user are as follows (the corresponding HTTP verb is in square brackets).
- 200 OK – [GET] : the server successfully returns the requested data, which is Idempotent.
- 201 CREATED – [POST/PUT/PATCH] : Data is CREATED or modified successfully.
- 202 Accepted – [*] : indicates that a request has been queued in the background.
- 204 NO CONTENT – [DELETE] : The user succeeded in deleting data.
- 400 INVALID REQUEST – [POST/PUT/PATCH] : An error occurs in the REQUEST sent by the user. The server does not create or modify data. The operation is idempotency.
- 401 Unauthorized – [*] : Indicates that the user does not have permission (the token, user name, or password is incorrect).
- 403 Forbidden – [*] Indicates that the user is authorized (as opposed to the 401 error), but access is Forbidden.
- 404 NOT FOUND – [*] : The user requested a record that did NOT exist, the server did NOT perform the operation, the operation is idempotent.
- 406 Not Acceptable – [GET] : The format requested by the user is Not available (for example, the user requested JSON format, but only XML format).
- 410 Gone -[GET] : The requested resource is permanently deleted and cannot be retrieved.
- 422 Unprocesable Entity – [POST/PUT/PATCH] An authentication error occurred while creating an object.
- 500 INTERNAL SERVER ERROR – [*] : An ERROR occurs on the SERVER, and users cannot determine whether the request is successful.
See here for a complete list of status codes.
Viii. Error Handling
If the status code is 4XX, an error message should be returned to the user. In general, error is returned as the key name and the error message as the key value.
{ error: "Invalid API key" } Copy the code
9. Return the result
For different operations, the server should return results to the user that conform to the following specifications.
- GET /collection: Returns a list (array) of resource objects
- GET/Collection /resource: Returns a single resource object
- POST/Collection: Returns the newly generated resource object
- PUT/Collection/Resource: Returns the complete resource object
- PATCH/Collection/Resource: Returns the complete resource object
- DELETE /collection/resource: Returns an empty document
Ten, Hypermedia API
RESTful apis are best for Hypermedia, that is, return results that provide links to other API methods so that the user knows what to do next without looking up the documentation.
For example, when a user makes a request to the root directory of api.example.com, they get a document like this.
{"link": { "rel": "collection https://www.example.com/zoos", "href": "https://api.example.com/zoos", "title": "List of zoos", "type": "application/vnd.yourformat+json" }} Copy the code
The above code shows that the document has a link property that the user reads to know what API to call next. Rel represents the relationship between the API and the current url (and gives the url of the collection), href represents the path to the API, title represents the title of the API, and type represents the return type.
The design of the Hypermedia API is called HATEOAS. 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", "authorizations_url": "https://api.github.com/authorizations", // ... } Copy the code
As you can see from the above, if you want to get information about the current user, you should go to api.github.com/user and get the following result.
{ "message": "Requires authentication", "documentation_url": "https://developer.github.com/v3" } Copy the code
The above code shows that the server gives the prompt, along with the url of the document.
Xi. Miscellaneous
(1) API authentication should use OAuth 2.0 framework.
(2) The data format returned by the server should be JSON instead of XML.
(after)