RESTful API is a relatively mature set of API design theory of Internet applications.

agreement

The API always uses HTTPs to communicate with users.

The domain name

Try to deploy the API under a private domain name.

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

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.

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.

Such as:

HTTP: / / https://api.example.com/v1/zoos / / get all the information / / https://api.example.com/v1/animals for all animals zooCopy the code

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.Copy the code

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.Copy the code

Here are some examples.

GET /zoos: lists all zoos POST /zoos: creates a new zoo GET /zoos/ID: obtains information about a specified zoo PUT /zoos/ID: updates information about a specified zoo (provides all information about the zoo) PATCH /zoos/ID: DELETE /zoos/ID: deletes a zoo GET /zoos/ID/animals: lists all animals for a specified zoo DELETE /zoos/ID/animals/ID: Deletes a specified animal from a specified zooCopy the code

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: Specify 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 conditionCopy the code

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.

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 is queued in the background (an asynchronous task). 204 NO CONTENT - [DELETE] : Indicates that the user deleted data successfully. 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.Copy the code

See here for a complete list of status codes.

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

Returns 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 a newly generated resource object. PATCH /collection/resource: Returns the full resource object DELETE /collection/resource: returns an empty documentCopy the code

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.

other

(1) API authentication should use OAuth 2.0 framework.

(2) The data format returned by the server should be JSON instead of XML.

practice

  1. Use HTTP or HTTPS
  2. The API can be a specific domain name or a master domain name.
  3. Put the version number of the API into the URL.
  4. Urls can’t have verbs, they can only have nouns, they should be plural.
  5. The specific types of operations on resources are represented by HTTP verbs.
  6. Common HTTP verbs include POST, GET, PUT, and DELETT, which correspond to CRUD (add, delete, modify, and search).
  7. Paging, sorting, Filtering, and so on are displayed in Filtering, known as query parameters
  8. The commonly used status codes are as follows: 200 OK/401 Unauthorized/403 Forbidden/404 NOT FOUND/500 INTERNAL SERVER ERROR
  9. Error handling: Error is returned as the key name and error message as the key value.
  10. The server returns results that conform to the specification to the user for different operations.
  11. RESTful API is best to do Hypermedia, generally to do, but there will be API management system or documentation.

reference

  • RESTful API design Guide