HTTP API Design Guide from Heroku (Chinese version)

Source: Internet
Author: User
Tags ranges

Translated from: Http://get.jobdeer.com/343.get

HTTP API Design Guide from Heroku (Chinese version)

Translation by @Easy

Brief introduction

This guide Chinese translator for @Easy, he is the first Internet talent auction website Jobdeer.com founder. Reproduced please retain this information.

This guide describes the design practices of a series of Http+json APIs that come from and unfold in the work of the Heroku Platform API. This guide guides the development of the Heroku internal API, and we want to be able to help API designers outside of Heroku.

...

Directory

Basis

    • Always use TLS
    • With the version number in the accepts head
    • Support Caching via Etags
    • Tracking requests with Request-ids
    • Use ranges to split pages

Request

    • Return the appropriate status code
    • Always return the full resource
    • Receive JSON sequence in request body
    • Use a consistent path format
    • lowercase all paths and attributes
    • Support for non-ID parameters as a shortcut
    • Less nesting with paths

Response

    • Always provide resource (UU) ID
    • Provides a standard time stamp
    • UTC time using the ISO8601 format
    • Embed foreign key data
    • Always generate structured error messages
    • Show the status of the frequency limit
    • Compress JSON data in all responses

Documents and other

    • Provides machine-readable JSON format
    • Provides human-readable documentation
    • Provides an example of an executable
    • Describe stability
Base always uses TLS

Always use TLS (that is, HTTPS) to access the API, there is no need to point out when to use, when not needed, just use it at all times.

Return 403 Forbidden for all non-TLS requests, and do not use redirects, which will allow some undesirable client behavior without any benefit. Clients that rely on redirection will double the traffic and make TLS meaningless-sensitive data has been sent out on the first request.

With the version number in the accepts head

Assign a version to the API from the beginning. Using the accepts header to send version information, you can use a custom content type, such as:

Application/vnd.heroku+json; Version=3

Instead of providing a default version, the client explicitly specifies which particular version it uses.

Support Caching via Etags

The ETAG header is taken in all requests to identify a specific version of the return resource. The user can check whether the content expires by providing the value of the If-none-match header in subsequent requests.

Tracking requests with Request-ids

Provide a Request-id header in each API corresponding to a unique UUID value. If both the server and the client record these values, they can be useful in tracking and debugging requests.

Use ranges to split pages

Paging through all responses that can generate large amounts of data. Use the Content-range header to mark paging requests. You can refer to this example to learn about request and response headers, status codes, Limit, sort, and page flipping: Heroku Platform API on Ranges

Request to return the appropriate status code

To return the appropriate status code for each request, a successful request should follow the following rules:

    • 200: When the GET request completes successfully, the delete or patch request is completed synchronously.

    • 201: The POST request is successfully completed in sync mode.

    • 202:post,delete or patch request submission succeeds and will be processed asynchronously later.

    • The 206:get request completed successfully, but only some of the data was returned. See Paging with ranges

Note the use of authentication and authentication errors:

    • 401 Unauthorized: The request failed because the user is not authenticated.
    • 403 Forbidden: The request failed because the user is not authorized to access a specific resource.

Returning the appropriate status code can provide more information about the error:

    • 422 unprocessable Entity: Your request server is understandable, but it contains illegal parameters.
    • 429 Too Many requests: request frequency is over-provisioned and try again later.
    • Internal Server Error: Server error, check the status of the site, or report a problem.

Based on the instructions of the HTTP response code specification, the status code is designed for user error and server error conditions.

Always return the full resource

For responses of 200 and 201, it is always possible to return the complete resource in the response (such as all properties of an object), including Put,patch and delete requests, such as:

$ curl-x DELETE \    https://service.com/apps/1f9b/domains/0fd4HTTP/-Okcontent-type:application/json; charset=utf-8... {  "2012-01-01t12:00:00z"}   

The 202 response does not include complete resources, such as:

$ curl-x DELETE \    https://service.com/apps/1f9b/dynos/05bdHTTP/202 acceptedcontent-type:application/ json;charset=utf-8... {}
Receive JSON sequence in request body

Instead of putting the extra information inside the form-encoded, put its JSON sequence in the body of the Put,patch or POST request. In order to respond to the same JSON sequence as the body symmetry (the author you are Virgo), such as:

$ curl-x POST https://service.com/apps     "Content-type:application/json"     ' {"name": "DemoApp"} ' {  "01234567-89ab-cdef-0123-456789abcdef",  ...}
Use a consistent path format

Resource Name

Use a complex number to name a resource, unless the resource is a single piece in the system (for example, in most systems, a user can have only one account). This allows consistency when you reference a specific resource.

Action

Use a endpoint format that does not require a specific action for a unique resource. This way, when specific actions are required, simply put them behind the standard actions prefixes to clearly describe them:

/resources/: resource/actions/: Action 

Such as:

/runs/{run_id}/actions/stop
lowercase all paths and attributes

Use lowercase letters and minus signs to name the path so that hostname can be aligned (the author you really are Virgo):

Service-api. Com/usersservice-api. Com/app-setups    

The same lowercase attribute, but using underscores to split, so that the property name in JavaScript can not be quoted:

"First"
Support for non-ID parameters as a shortcut

Sometimes it is troublesome to ask the end user to provide an ID to represent the resource, for example, the user may only think of Heroku appname, and the application itself is distinguished by the UUID. In this case, we can receive both the ID and the name:

$ curl https://service.com/apps/{app_id_or_name}$ curl https://service.com/apps/97addcf0-c182 $ curl https://service.com/apps/www-prod 

Never accept only names to exclude certain IDs.

Less nesting with paths

In a data model in which a parent child resource is nested, the path can be deeply nested:

/orgs/{org_id}/apps/{app_id}/dynos/{dyno_id}  

You can limit the number of nested layers by locating from the root path. Use nesting to identify the datasets inside the scope. For example, the top dyno belongs to an app, and the app belongs to an org example:

/orgs/{org_id}/orgs/{org_id}/apps/apps/{app_id}/apps/{app_id}/dynos/dynos/} 
Response always provides resource (UU) ID

Provide a default id attribute for each resource. The UUID is always used unless there is a special reason. Do not use IDs that are not globally unique between the instances of the service or the resources, especially the self-increment ID.

lowercase uuid in 8-4-4-4-12 format:

"01234567-89ab-cdef-0123-456789abcdef"
Provides a standard time stamp

Provide default Created_at and Updated_at timestamps for resources:

{  ...  "2012-01-01t12:00:00z",  "2012-01-01t13:00:00z",  ...}

If these timestamps really don't make sense to some resources, then you can also remove them.

UTC time using the ISO8601 format

Only accept and return UTC time, shown in ISO8601 format:

"2012-01-01T12:00:00Z"
Embed foreign key data

The foreign key reference is displayed through the serialized embedded object:

{  "Service-production",  "owner": {    "5d8201b0 ..."  },  ...}   

Rather than this:

{  "Service-production",  "5d8201b0 ...",  ...}  

This allows us to use the relevant data in inline without changing the format of the response, or introducing more high-level response fields:

{  "Service-production",  "owner": {    "5d8201b0 ...",    ...}   
Always generate structured error messages

Generates a consistent, structured response to the error body. Contains a machine-readable ID, a human-readable message, and an optional URL that points to more information about the error, and how to fix it:

429 Too Many requests
{  "id": "      rate_limit",  "" "account reached it API rate limit.","" https:// Docs.service.com/rate-limits"}    

Write a document for the format and ID of common errors for clients.

Show the status of the frequency limit

The frequency limit on the client can protect the health of the service and provide high-quality services to other clients. You can use the token bucket algorithm to quantify the request limit.

In the response header of each request, the number of requests remaining is returned through ratelimit-remaining.

Compress JSON data in all responses

Additional spaces increase the size of the response, and many user-friendly clients can automatically beautify the JSON output. Therefore, it is best to compress the JSON response:

{"beta":false, "Email":"[email protected]", "ID":"01234567-89ab-cdef-0123-456789abcdef", "  Last_login ":" 2012-01-01t12:00:00z ","created_at ":" 2012-01-01t12:00:00z ","updated_at ":" 2012-01-01t12:00:00z "}           

Don't do this:

{  "false,  ""[email protected]",  "01234567-89ab-cdef-0123-456789abcdef", "" 2012-01-01t12:00:00z "," "2012-01-01t12:00:00z", "" 2012-01-01t12:00:00z "}     

You might consider providing an alternative way to output a longer response for the client, such as by requesting parameters (such as? pretty=true) or through the Accept header (such as Accept:application/vnd.heroku+json; version=3; indent=4;).

Documentation and other available machine-readable JSON formats

Provide a machine-readable schema to describe your API, use PRMD to manage your schema, and use PRMD verify to make sure it passes validation.

Provides human-readable documentation

Provide human-readable documentation to help client developers understand your API.

If you use PRMD to create a schema, you can simply generate markdown endpoint-level documents with the PRMD Doc command.

In addition to the description of the endpoint level, provide a summary level of information, such as:

    • Authorization, including access to and use of authorized tokens.
    • The stability and version of the API, including how to select an existing API version.
    • Generic request and Response headers.
    • The serialized format of the error.
    • Examples of how clients of various languages use the API.
Provides an example of an executable

Provides an example of an executable so that the user can enter and see the API request that can be used directly at the terminal. The best case scenario is that these examples can be copied and pasted directly to minimize the cost of the user's trial API, such as:

$ export token=# Acquire from dashboard$ curl-is https://[email protected]/users

If you use PRMD to generate markdown documents, you get an executable example for free.

Describe stability

Describe the stability of your APIs, and which endpoint depend on their maturity, such as using prototype,development or production identification.

Refer to the Heroku API compatibility policy to learn which interfaces are stable and which are subject to change.

Once your API is declared as Production-ready and stable, do not make any non-forward-compatible modifications on the API version. If you need to do non-forward compatible modifications, create a new version number.

English original →https://github.com/interagent/http-api-design

This article was published by Easy on Get

HTTP API Design Guide from Heroku (Chinese version)

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.