RESTful API Design Practices

Source: Internet
Author: User

1. Distinguish crud by request type
Method Operation

Scene

GET Read

/cars

/cars/711

POST Create /cars
PUT Modify

/cars/711

/cars

PATCH Partial modifications /cars/711
DELETE Delete /cars/711

2. The resource uses nouns and uses plural

Get/tickets-Get Tickets list
GET/TICKETS/12-Get a separate ticket
Post/tickets-Create a new ticket
PUT/TICKETS/12-Update Ticket #12
PATCH/TICKETS/12-Partial Update ticket #12
DELETE/TICKETS/12-Delete Ticket #12

3.Get methods and query parameters should not involve state changes

Do not use GET for state changes,

Get/users/711?  /users/711/activate

4. Using child resources to express relationships

If a resource has a relationship with another resource, use a child resource:

Get/tickets/12/messages-Get ticket #12下的消息列表GET/TICKETS/12/MESSAGES/5-/tickets/12/messages-For ticket # 12 Create a new message PUT/TICKETS/12/MESSAGES/5-/tickets/12/messages/5-/TICKETS/12/MESSAGES/5-Delete Ticket # 12 under the number 5 message

5. Declaring serialization formats with HTTP headers

On both the client and server side, both sides need to know the format of the communication, the format specified in Http-header

Content-type Defining request formats
Accept defines a series of acceptable response formats

6. Filtering, sorting, search design

It is best to try to keep the basic resource URL simple. Complex result filters, sorting requirements, and advanced searches (when constrained to a single type of resource) can be easily implemented as query parameters on top of the base URL. Let's look at it in more detail below:

1) Filter : Use a unique query parameter for each field, you can implement filtering. For example, when you request a list of tickets through the "/tickets" terminal, you may want to limit the tickets that are sold. This can be done through a like

Get/tickets?state=open

Such a request to implement. The "state" here is a query parameter that implements the filtering function.

2) Sort : Similar to filtering, a generic parameter ordering can be used to describe the ordering rules. To accommodate complex ordering requirements, the sort parameters are taken as a comma-delimited list of fields, each of which may have a minus sign before each field to indicate descending order. Let's look at a few examples:

Get/tickets?sort=-priority-Get a list of tickets, sort by descending priority field Get/tickets?sort=-priority,created_at-get a list of tickets and sort in descending order by the priorities field. In a particular priority, the earlier tickets are in front

3) Search : Sometimes the basic filtering can not meet the demand, then you need the power of full-text search. You may already be using ElasticSearch or other Lucene-based search techniques. When a full-text search is used as a mechanism to obtain a resource instance of a particular resource, it can be exposed to the API as a query parameter for the resource terminal, which we call "Q". Search-class queries should be delivered directly to the search engine, and the API's output should have the same format, with a normal list as the result.
By combining these together, we can create some of the following queries:

Get/tickets?sort=-updated_at-Get the most recently updated ticket get/tickets?state=closed&sort=-updated_at-Get the most recent update and the status is off the ticket. Get/tickets?q=return&state=open&sort=-priority,created_at-Gets the highest-priority, first-created, state-open ticket with ' return ' on the ticket.

4) General Query definition method

To make the API usage experience more enjoyable for ordinary users, consider wrapping the set of conditions into a restful path that is easy to access. For example, the query for the most recently closed tickets can be packaged as

Get/tickets/recently_closed

5) Limit query return fields

The user of the API does not always need a complete representation of a resource. The ability to choose a return field has been a long-standing feature that allows API users to minimize network congestion and speed up their calls to the API.
Use a field query parameter that contains a comma-delimited list of fields. For example, the following request will have just enough information to show an ordered list of tickets:

Get/tickets?fields=id,subject,customer_name,updated_at&state=open&sort=-updated_at

6) Paging pagination

Use limit and offset. Implement paging, default limit=20 and offset=0;

Get/cars?offset=10&limit=5

To send the total to the client, use the custom HTTP header: X-total-count.

Link to next or previous page in the HTTP header, follow the link rules:

Link: //blog.mwaysolutions.com/sample/api/v1/cars?offset=15&limit=5>; rel= "Next", //blog.mwaysolutions.com/sample/api/v1/cars?offset=50&limit=3>; rel= "Last", //blog.mwaysolutions.com/sample/api/v1/cars?offset=0&limit=5>; rel= "First", //blog.mwaysolutions.com/sample/api/v1/cars?offset=5&limit=5>; rel= "Prev", 

7. Updates and creation should return a resource description

A PUT, POST, or PATCH call may cause changes to certain fields of the specified resource, which are not listed in the supplied parameter (for example, Created_at or Updated_at). To prevent API users from calling the API again in order to obtain updated resources, the API should be returned as part of the response for the updated (or created) resource.

As an example of a POST operation that creates an activity, use an HTTP 201 status code and then include a location header to point to the URL of the new resource.

8. Return only JSON

9. Field name writing format Unified

Select a method: Snake_case vs CamelCase

10. Formatted and supported gzip by default

An API that provides white-space character compression output, viewing results from a browser is not beautiful. While some of the ordered query parameters (such as pretty=true) can be provided for beautiful printing to take effect, an API that can be printed beautifully by default is more approachable. The cost of additional data transfer is negligible, especially if you compare the cost of gzip compression.
Consider some use cases: assume that an API consumer is debugging and has its own code to print out the data received from the API-this should be readable by default. Or, if the consumer catches their code-generated URL and accesses it directly from the browser-this should be readable by default. These are small things. Doing small things can make an API more enjoyable to use

11. Error Design

Just like an HTML error page shows a useful error message to a visitor, an API should provide useful error information in a known, usable format. The representation of the error should be no different from any other resource, just a set of its own fields.
The API should always return a meaningful HTTP status code. API errors are typically divided into two types: the 400-series status code representing the client problem and the 500-series status code that represents the server problem. In the simplest case, the API should be a standardized representation of the easy-to-use JSON format as a 400-series error. This also applies to the 500 series error codes if possible (meaning, if load balancing and reverse proxies can create custom error entities).
A JSON-formatted error message body should provide the developer with a few things-a useful error message, a unique error code that can be used to query the document for detailed error information, and a possible detailed description. Such a JSON-formatted output might look like this:

{"code": 1234,"message": "Something bad happened:(","description": "More details about the Error here "}

Error validation of put, patch, and post requests will require a field decomposition. The following may be the best pattern: use a fixed top-level error code to validate errors, and provide detailed error information in additional fields, like this:

{"code": 1024x768,"message": "Validation Failed","errors" : [{    "code": 5432,     "field": "First_Name","    message": "First name cannot has fancy characters"},{    " Code ": 5622,    " field ":" Password ",    " message ":" Password cannot be blank "}]} 

12.HTTP Status Code

HTTP defines a set of meaningful status codes that can be returned from the API. This code can be used to help API users handle different responses accordingly. I've made a short list of those that you're bound to use:

    • OK (Success)-a response to a successful get, PUT, PATCH, or delete. can also be used for a post that does not generate a Create activity
    • 201 Created (created)-a response to a post that caused the creation of an activity. At the same time, a location header information is used to point to the location of the new resource-Response to a POST, which results in a creation. Should is combined with a location header pointing to the location of the new resource
    • 204 no Content-response to a request that does not return principal information (like a delete request) at a time
    • 304 not Modified (unmodified)-use 304 when using HTTP cache header information
    • (Bad Request)-request is malformed, such as unable to parse the request body
    • 401 Unauthorized (unauthorized)-When invalid authentication details are not provided or provided. If the API is used from a browser, it can also be used to trigger a pop-up authentication request
    • 403 Forbidden (no access)-when authentication is successful but authenticated users do not have access to the resource
    • 404 Not Found (not found)-when a resource that does not exist is requested
    • 405 Method Not allowed (methods forbidden)-when an HTTP method that is forbidden by the authenticated user is requested
    • 410 Gone (Deleted)-Indicates that the resource is no longer available at the terminal. Useful as a generic response when accessing older versions of the API
    • 415 Unsupported media type (not supported)-If the request contains an incorrect content type
    • 422 unprocessable Entity (unable to process entities)-use when a validation error occurs
    • 429 Too Many requests (too many requests)-when a request is denied due to an access rate limit

RESTful API Design Practices

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.