RESTful API Design Guide

Source: Internet
Author: User

Excerpt from: Http://www.ruanyifeng.com/blog/2014/05/restful_api http://www.ruanyifeng.com/blog/2011/09/restful.html

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 one of the more mature API design theories for Internet applications

First, the agreement

The API communicates with the user protocol, always using the HTTPS protocol.

Second, the domain name

1. The API should be deployed under the dedicated domain name as much as possible (there is a cross-domain issue in this case)

https://api.example.com

2. If the API is determined to be simple, there will be no further expansion, 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. GitHub uses this approach.

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.

    • HTTPS://API.EXAMPLE.COM/V1/ZOOS?LIMIT=10: Specifies the number of records returned

    • HTTPS://API.EXAMPLE.COM/V1/ZOOS?OFFSET=10: Specifies the start position of the returned record

    • HTTPS://API.EXAMPLE.COM/V1/ZOOS?PAGE=2&PER_PAGE=100: Specify pages, and the number of records per page

    • HTTPS://API.EXAMPLE.COM/V1/ZOOS?SORTBY=NAME&ORDER=ASC: Specifies which attribute the returned result is sorted by, and the sort order

    • Https://api.example.com/v1/zoos?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.

    • 202 Accepted-[*]: Indicates that a request has entered the background queue (asynchronous task)

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

    • 401 Unauthorized-[*]: Indicates that the user does not have permissions (token, user name, password error).

    • 403 Forbidden-[*] indicates that the user is authorized (as opposed to a 401 error), but access is forbidden.

    • 404 Not FOUND-[*]: The user makes a request against a nonexistent record, the server does not operate, the operation is idempotent.

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

    • 410 Gone-[get]: The resource requested by the user is permanently deleted and will no longer be available.

    • 422 unprocesable Entity-[Post/put/patch] A validation error occurs when an object is created.

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

{    "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   " , // ...}  
 < Span class= "token punctuation" > from the above you can see that if you want to get information about the current user, Should go to visit Api.github.com/user, and then get the following results. 


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



RESTful API Design Guide

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.