What is a Restful

  • Essence: a style of software architecture
  • Core: Resource-oriented
  • Resource: an entity on a network, a specific piece of information on a network
  • Problems solved: 1. Reduce the complexity of development; 2. Improve system scalability

Restful is an architectural guideline that all Web applications should follow.

This section describes HTTP protocol functions

The HTTP protocol – the url

HTTP is an application layer protocol, characterized by simplicity and speed.

schema://host[:port]/path[?query-string][#anchor]

  • == Scheme == Specifies the protocol used at the lower level (e.g. HTTP, HTTPS, FTP)
  • ==host== IP address or domain name of the server
  • ==port== Server port number. The default value is 80
  • ==path== Path for accessing resources
  • ==query-string== Data sent to the HTTP server
  • = = the anchor = = anchor

HTTP protocol – Request

Format: request line, message header, request message

The request line

  • The format is Method request-URL http-version CRLF

For example,

  • GET / HTTP/1.1 CRLF

Request method

  • ==GET== Requests to obtain the resource identified by requesr-URI
  • ==POST== Append the salary data to the resource identified by request-URI
  • ==HEAD== Request a response message header for the resource identified by request-URI
  • ==PUT== Requests the server to store a resource and identify it with request-URI
  • ==DELETE== Requests the server to DELETE the resource identified by request-URI
  • ==OPTIONS== Requests queries about server performance or resource-related OPTIONS and requirements

HTTP protocol – response

Composition format: status line, message header, response body

The status line

  • HTTP-Version Status-Code Reason-Phrase CRLF
  • For example, HTTP /1.1 200 OK

Common status code

  • 200 OK // The client request is successful
  • 400 Bad Request // The client Request has a syntax error and cannot be understood by the server
  • 401 Unauthorized // The server received the request but declined to provide the service
  • 404 Not Found // The requested resource does Not exist
  • 500 Internal Server Error // The Server sent an unexpected Error
  • 503 Server Unavailable // The Server cannot process requests from clients

How Restful architectures differ from other architectures

SOAP WebService
  • WebService is a remote call technology across programming languages and operating system platforms.
  • When WebService sends request and receives result through HTTP, it uses XML format to encapsulate, and adds some SPECIAL HTTP headers. These special HTTP headers and XML content format are SOAP protocol.
Efficiency and ease of use
  • SOAP’s performance in SOAP processing has deteriorated due to various requirements that expand the content of its own protocol. There has also been an increase in ease of use and cost of learning.

  • Restful simplifies bad design for developers because of its resource-oriented interface design and operational abstraction, while maximizing Http’s original application protocol design philosophy.

    security
  • Restful is suitable for resource-based service interfaces and is especially suitable for scenarios that require high efficiency but low security.

  • SOAP’s maturity can facilitate the design of security-sensitive interfaces that need to be provided to multiple development languages. So I don’t think it makes sense to say that design patterns are going to be dominant. It all depends on the application scenario.

How to design Restful apis

agreement

The API always uses HTTPS to communicate with users.

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
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.

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

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.

HTTP other
  • API authentication should use the OAuth 2.0 framework.
  • The data format returned by the server should be JSON rather than XML.

The resources

Restful API Actual API Design Guide Understanding Restful ARCHITECTURE [Restful API Design Reference List](