RESTful API design specifications

Brief introduction

REST (English: Representational State Transfer , referred to as REST ) architectural style describes a network system, such as a web application. It first appeared in 2000, Roy Fielding's doctoral thesis, he is one of the principal authors of the HTTP specification. In the current three major Web service interaction scheme, REST compared to SOAP (Simple Object Access protocol, Simple Object Access Protocol) and XML-RPC is more straightforward, either processed or URL for Payload encoding, REST are tend to design and implement a more simple and lightweight way. It is noteworthy that REST does not have a clear standard, but rather is a design style.

Definition: In simple terms REST is an architecture style (instead of the standard), a distributed application layer systems solution.

Objective: Client and Server side further decoupling.

  • REST has nothing to do with technology, represent a style of software architecture, REST is Representational State Transfer short, the Chinese translation of "transfer of state characterized" as
  • REST look like from the perspective of resources throughout the network, which will be identified in the distribution of resources in the network of a node by its URL, the client application to obtain the resources characterized by URL, access to these applications characterize the resulting change the status of these
  • REST has nothing to do with technology, represent a style of software architecture, REST is Representational State Transfer short, the Chinese translation of "transfer of state characterized" as
  • All of the data, but was acquired by the network or the operation (CRUD) data, all resources, all data will be treated as REST resources are the most essential attribute different from other architectural styles
  • For this resource-oriented REST architectural style, it was suggested that a new structure concept, namely: resource-oriented architecture (ROA: Resource Oriented Architecture)

 

First, the agreement

API and user's communication protocol, always using HTTPs protocol .

Second, the domain name

1. API should try to be deployed under the private domain name, (in which case there will be cross-domain problems)

https://api.example.com

2. If it is determined API is very simple, there will be no further extension may be considered placed under the main domain name.

https://example.org/api/

Third, the version (Versioning)

API version number should be placed in URL.

https://api.example.com/v1/

Another approach is the version number in the HTTP header information, but not as into convenient and intuitive URL. Github this practice.

Fourth, the path (Endpoint)

Path, also known as "the end" (endpoint), represent specific URL API.

In a RESTful architecture, each URL represents a resource (resource), so the URL can not have a verb, a noun only, but also used the term often correspond to the name of the database table. In general, the table in the database are the same kinds of records "collection" (collection), so the API should also use plural nouns.

For example, there is an API to provide information Zoo (Zoo), further including a variety of animals and employee information, it should be designed such that the path below.

  • https://api.example.com/v1/zoos

  • https://api.example.com/v1/animals

  • https://api.example.com/v1/employees

Five, HTTP verb

For particular resource type of operation, represented by the HTTP verbs.

Common HTTP verbs are the following five (in brackets is the corresponding SQL commands).

  • GET (SELECT): Remove the resource from the server (one or more).

  • POST (CREATE): a new resource on the server.

  • PUT (UPDATE): update the resource (after the complete resources provided by the client to change) in the server.

  • PATCH (UPDATE): Updating Resource (provided by the client to change the properties) in the server.

  • DELETE (DELETE): Delete the resource from the server.

There are two less commonly used HTTP verbs.

  • HEAD: Gets the metadata resources.

  • OPTIONS: access to information, which properties on the resources of the client can be changed.

Here are some examples.

  • GET / zoos: List all zoo

  • POST / zoos: Create a new zoo

  • GET / zoos / ID: obtaining information about a specified Zoo

  • PUT / zoos / ID: Updates a specified Zoo (providing all the information the zoo)

  • PATCH / zoos / ID: update a specified Zoo (zoo information providing section)

  • DELETE / zoos / ID: delete a zoo

  • GET / zoos / ID / animals: List all the animals of a given zoo

  • DELETE / zoos / ID / animals / ID: delete the specified a specified animal zoo

Sixth, filtering information (Filtering)

If a large number of records, the server can not all they are returned to the user. API should provide parameters, filtering results are returned.

Here are some common parameters.

  • https://api.example.com/v1/zoos?limit=10: Specifies the number of records returned

  • https://api.example.com/v1/zoos?offset=10: Returns the specified record start position

  • https://api.example.com/v1/zoos?page=2&per_page=100: Specifies the first few pages, as well as the number of records per page

  • https://api.example.com/v1/zoos?sortby=name&order=asc: Specifies which returns the results sorted by attribute, and sort order

  • https://api.example.com/v1/zoos?animal_type_id=1: Specify Filter Conditions

The redundancy allows the design parameters, i.e. parameters allow API and URL path occasional duplicate. For example, GET / zoo / ID / animals and GET / animals? Zoo_id = ID is the same meaning.

Seven, the status code (Status Codes)

Server returns to the user code and status message, a number of common are the following (in brackets is the HTTP status code corresponding verb).

  • 200 OK - [GET]: the server returns the data requested by the user successfully, the operation is idempotent (Idempotent).

  • 201 CREATED - [POST / PUT / PATCH]: new or modified user data successfully.

  • 202 Accepted - [*]: indicates a request has been queued into the background (asynchronous task)

  • 204 NO CONTENT - [DELETE]: Delete user data successfully.

  • 400 INVALID REQUEST - [POST / PUT / PATCH]: request issued by a user mistake, the server does not create or modify the operation data, the operation is idempotent.

  • 401 Unauthorized - [*]: indicates that the user does not have permission (Token, username, password error).

  • 403 Forbidden - [*] indicates that the user is authorized (and 401 relative error), but access is prohibited.

  • 404 NOT FOUND - [*]: user issues a request for recording is not present, the server is not operated, the operation is idempotent.

  • 406 Not Acceptable - [GET]: the format requested by the user is not available (such as JSON format requested by the user, but only the XML format).

  • 410 Gone - [GET]: user request resources are permanently removed, and will not be obtained.

  • 422 Unprocesable entity - [POST / PUT / PATCH] When an object is created, a verification error occurs.

  • 500 INTERNAL SERVER ERROR - [*]: server error occurs, the user will be unable to determine whether the request is sent successfully.

 See the complete list of status codes here .

Eight, Error Handling (Error handling)

If the status code 4xx, it should return an error message to the user. In general, the error information will be returned as the key name as a key to the error message.

{
    error: "Invalid API key"
}

Nine, return results

For different operations, the results returned by the user to the server should meet the following specifications.

  • GET / collection: Returns the resource object list (array)

  • GET / collection / resource: return a single resource object

  • POST / collection: Returns the newly created 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

十、Hypermedia API

RESTful API is best to do Hypermedia, ie, the returned results provide links, even to other API methods, so that the user does not check the documents, but also know what to do next.

For example, when a user issues a request to the root api.example.com, such a document will be.

{"link": {
  "rel":   "collection https://www.example.com/zoos",
  "href":  "https://api.example.com/zoos",
  "title": "List of zoos",
  "type":  "application/vnd.yourformat+json"
}}

The above code indicates that the document has a link attribute, user attribute read this will know what the next step API calls. rel indicates that the current API URL (collection relationship, and gives the collection URL), href represents the path of the API, title represents the title of the API, type indicate the return type.

Hypermedia API design is called HATEOAS . Github's API is this design, visit api.github.com will get a list of URLs of all available API.

{
  "current_user_url": "https://api.github.com/user",
  "authorizations_url": "https://api.github.com/authorizations",
  // ...
}
从上面可以看到,如果想获取当前用户的信息,应该去访问api.github.com/user,然后就得到了下面结果。
{
  "message": "Requires authentication",
  "documentation_url": "https://developer.github.com/v3"
}

The above code indicates that the server gives prompt information, and the URL of the document.

other

Authentication (1) API should use OAuth 2.0 framework.

(2) the server returns data format should try to use JSON, avoid the use of XML.

 

Guess you like

Origin www.cnblogs.com/XLHIT/p/11627767.html