RESTful Style API

Source: Internet
Author: User

One: agreement

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

Two: Domain name

The API should be deployed under a dedicated domain name whenever possible.

Https://api.example.com

If you determine that the API is simple, there is no further extension, consider placing it under the primary domain name.

https://example.org/api/
Three: Version

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.

Four: Path

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/Zooshttps://api.example.com/v1/Animalshttps://api.example.com/v1/employees
V: HTTP verb

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.

Here are some examples.

 get /zoos: List all zoos post /zoos: Create a new zoo  get /zoos/id  : Get information about a specified zoo  put /zoos/id  : Update information for a specified 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 given zoo  delete /zoos/id /animals/id : Deletes a specified animal from a specified zoo 
VI: Filter Information

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.

limit=: Specifies the number of returned records offset=: Specifies the start position of the returned record. page =2&per_page=: Specifies the number of pages, and how many records per page. SortBy=name&order=ASC: Specifies which attribute the returned results are sorted by, and the sort order. animal_type_id=1: Specify 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.

Seven: status code

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 returned the data requested by the user, and the operation was Idempotent (idempotent). 201CREATED-[post/PUT/PATCH]: User new or modified data succeeded. 202Accepted-[*]: Indicates that a request has entered the background queue (asynchronous task)204NO CONTENT-[DELETE]: User deleted data successfully.  -INVALID REQUEST-[post/PUT/PATCH]: The user made a request error, the server did not create new or modify the data operation, the operation is idempotent. 401Unauthorized-[*]: Indicates that the user does not have permissions (token, user name, password error). 403Forbidden-[*] Indicates that the user is authorized (relative to the 401 error), but access is forbidden. 404  notFOUND-[*]: The user made a request for a nonexistent record, the server did not operate, the operation is idempotent. 406  notAcceptable-[GET]: User requested format is not available (such as user request JSON format, but only XML format). 410Gone-[GET]: The resource requested by the user is permanently deleted and will no longer be available. 422unprocesable entity-[post/PUT/PATCH] A validation error occurs when an object is created.  -INTERNAL Server Error-[*]: The server has errors, the user will not be able to determine whether the request was made successfully.

Eight: Error 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"}
Nine: Return 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 (array)GET /collection//collection: Returns the newly generated resource object PUT /collection//collection/resource: Returns the full resource object DELETE /collection/ Resource: Returns an empty document

Ten: 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 ",  // ...}

As you can see from the above, if you want to get information about the current user, you should go to the api.github.com/user and get the results below.

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

article turned from:http://www.ruanyifeng.com/blog/2011/09/restful

RESTful Style API

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.