In the project, you need to compose an API for the background service. At the beginning of contact, and did not consider too much, just want to provide a URL, the server through the URL to query, create, update and so on. However, after understanding the relevant specifications, it is found that the design of the API is not so simple, far from the problem of the URL, but the overall architecture of a communication protocol
1. Use the GET, POST, PUT, delete request modes
Request mode can also be said to be action, data transmission mode, usually we have a form in the Web get, post two kinds, and in HTTP, there are issued these kinds.
Get (SELECT): Gets a specific resource or a list of resources from the server.
POST (Create): Creates a new resource on the server.
PUT (update): Updates a resource on the server in a holistic manner.
PATCH (update): Only one property of the server's previous resource is updated.
Delete: Deletes a resource on the server.
2. Use nouns rather than verbs
Resource Resources |
GET Read |
POST Create |
PUT Modify |
DELETE |
/cars |
Back to Cars Collection |
Create a new resource |
Batch Update cars |
Remove All cars |
/cars/711 |
Returns a specific car |
This method does not allow (405) |
To update a specified resource |
Good at assigning resources |
Do not use:
/getallcars
/createnewcar
/deleteallredcars
3.Get methods and query parameters should not involve state changes
Use the PUT, POST , and DELETE methods instead of the get method to change the state, and do not use get for state changes:
Get/users/711?activate
Get/users/711/activate
4. Using plural nouns
Do not confuse noun singular and plural, in order to keep it simple, use complex numbers only for all resources.
/cars, not/car.
/users, not/user.
/products, not/product.
/settings and Deploy/setting
5. Using child resources to express relationships
If a resource has a relationship with another resource, use a child resource:
get/cars/711/drivers/returns all drivers for car 711
GET/CARS/711/DRIVERS/4 back to Car # 4th driver 711
6. Provide the collection with
filtering sorting options and paging functions
For example, when there is too much data, we should unify the API request parameters when we need to make paging requests to the data. Common to have these.
limit=10
Specify the number of returned records
offset=10
Specifies the start position of the returned record.
page=2&per_page=100
Specify the number of pages, and how many records per page.
sortby=name&order=asc
Specifies which property the returned result is sorted by, and the sort order.
animal_type_id=1
Specify filter criteria
Filtering filter :
Filter by using unique query parameters:
Get/cars?color=red back to the red cars
get/cars?seats<=2 returns a cars collection of less than two seats
sorting Sort by:
Allow sorting on multiple fields
Get/cars?sort=-manufactorer,+model
This is the car collection that is returned according to the producer descending order and the model ascending
Field selection
The mobile side can display some of these fields, they actually do not need all the fields of a resource, give the API consumer a choice field ability, this will reduce network traffic, improve API usability.
Get/cars?fields=manufacturer,model,id,color
Paging Sub-page
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:
7. Versioning your API
The development of the API directly related to whether the app can be used normally, if the original operation of the normal API, a sudden change, then the previous use of the API app may not work properly. The app is not likely to force users to actively upgrade, so the API version to solve this problem. In other words, multiple versions of the API are running concurrently and are guaranteed to work properly.
According to restful specifications, different versions should also use the same API URL, the header information to determine the version, and then call different versions of the program for processing. But this is obviously a huge cost to development. Make the API version mandatory, do not publish a version-free API, use simple numbers, avoid decimal points such as 2.5.
There are several ways to solve this problem:
1. The new version is compatible with the old version, all the previous versions of the actions, fields, operations, can be implemented in the new version, but obviously such maintenance costs are very large;
2. Different versions, with different URLs to provide services, in the URL by V1, v2 to differentiate the version number, such as V2.api.xxx.com/user, or HTTP://API.DOMAIN.COM/V2 or http:// Www.domain.com/api/v2.
3. Each interface has its own version, typically adding a version parameter to the interface.
8.json Data types
- Number: integer or floating-point number
- String: Strings
- Boolean:true or False
- Array: arrays are enclosed in square brackets []
- Object: Objects are contained in curly braces {}
- Null: null Type
Therefore, the data type of the transmission cannot exceed these six data types. Previously, we have tried to transfer the date type, it will be similar to the "January 7, 2016 09:17 42 seconds gmt+08:00" Such a string, which will cause problems in the conversion, different analytic library resolution may be different, some may be confused, some may be directly abnormal. To avoid errors, you have to do special processing, you do the analysis manually. To eradicate this problem, the best solution is to use a number of milliseconds or a string to represent the date.
The data structure returned
{ code:0, "Success", }}
- Code: Return code, 0 for success, not 0 for various different errors
- Message: Description information, success is "Success", error message when wrong
- Data: Returned on success, type is object or array
The data field will only be returned if the request succeeds. The data type is scoped to an object or array, and the object is returned when the requested data is a single object, or an array of objects when the requested data is a list. It is important to note that you should not pass data into a string or number, even if the request requires only one data, such as token, the returned data should be:
// correct data: { token: abcdedf } // error data: abcdefg 9. Handling errors using HTTP status codes
Different errors need to define a different return code, the client-side error and the server error also to distinguish, such as 1XX indicates the client error, 2XX indicates the server error
If your API is not error-handling is difficult, just return 500 and the error stack is not necessarily useful
HTTP status Code provides 70 errors, we only need to use 10 or so:
200–ok– everything's fine.
201–ok– a new resource has been created successfully
204–ok– resources have been successful at
304–not modified– client uses cached data
400–bad request– request is invalid and requires additional details to explain such as "JSON is invalid"
401–unauthorized– request requires user authentication
The 403–forbidden– server has understood the request, but denial of service or access to such a request is not allowed.
404–not found– did not find the resource
422–unprocessable entity– is only used when the server cannot process the entity, the image cannot be formatted, or the critical field is lost.
500–internal Server ERROR–API Developers should avoid this error.
Use verbose error wrapping error:
{
"Errors": [
{
"Usermessage": "Sorry, the requested resource does not exist",
"Internalmessage": "No car found in the database",
"Code": 34,
"More Info": "http://dev.mwaysolutions.com/blog/api/v1/errors/12345"
}
]
}
10. Allow overriding of HTTP methods
Some proxies support only the POST and get methods, in order to support the RESTful API with these limited methods, a way to overwrite the HTTP original method is needed.
Use the custom HTTP header x-http-method-override to overwrite the Post method.
Restful API Design Reference principles