WEB API design experience and summary

Source: Internet
Author: User
Tags response code

In the era of mobile Internet, Web services have become the main means of interconnection and integration between heterogeneous systems, and various Web services are built using RESTful Web APIs. In the form of an HTTP protocol. Send requests in a get/post manner, returning data in JSON format (data is smaller and self-descriptive). The benefits and weaknesses of the rest API are not covered here. A whole bunch of stuff on the Internet. Say today, how to build a good rest API?

At present, the major Internet companies, their own rest API design has its own standards, their API design is very mature. So how do we better design our interfaces to improve usability, ease of use, maintainability, and scalability of our APIs?

  I. API Design Solutions
1. HTTP requests are divided into URL convention rules, request parameter rules
URL rule: Http://{server}/{product}/{version}/{logic}/{method}? {query_string}

Server: For the specific service domain name
Product: For the Application project name
Version: for the specific release number, to facilitate future function expansion, can be tentatively v1, v2
Logic: A preliminary division of specific business logic, such as a backend management approach, and an app-side request method
Method: A specific business approach

The specific request parameters are determined by the method specified, all as the list of parameters for the HTTP get/post.

Many people here ask why the method and version are placed in the URI.

This allows the API to be versioned, facilitates versioning, and facilitates future streaming of APIs. Of course, whether to put the version information into the URL or into the request header, there has been a very heated controversy, each has its own truth. I personally think it would be better to put it in the URL. Specific people or according to their own business scenarios, comprehensive consideration it.


2. HTTP response Rules
The HTTP response code is 200 and returns the result as a JSON string:
If the response results are correct, the results are as follows:
{
The data: {//Request, object or array can be
User_id:123,
User_name: "ZWZ",
User_avatar_url: "Http://www.abc.com/1.jpg"
...
},
msg: "Done",//Request status Description, tune trial
Success:1,
Code ": 1001,//Custom status code for business
Extra: {//Other extended data, fields, content variable
Type:1,
Desc: "Sign in successfully!" "
}
}

If the response result fails, the following result is returned:
{
The data: {//Request, object or array can be
},
Msg: "Internal Server Error",//Request status Description, tune trial
success:0,
CODE:5001,//Business Custom status code
Extra: {
}
}

3. Auth Permission Verification

API authorization, there are many scenarios, the current Mature OAuth 2.0 framework, etc., but the simplest is to use the Http Header to accomplish this goal. Pass tokens through the Header. To implement permission validation.


4. API in the design, it is best not to the business error code and HTTP status code binding, redefine a set of business error code, to distinguish the status code of HTTP.
The definition of status code also preferably has a set of specifications, similar to the status code of HTTP, can be related to users, licensing-related, a variety of business, do a simple classification.
Code Business Custom Status Code Definition example
Licensing-related
1001: No Access
1002:access_token Expired
1003:unique_token invalid
...

User-related
2001: Not logged in
2002: User Information Error
2003: The user does not exist

Business related
3001: Business XXX
3002: Business XXX

System exceptions
5001:internal Server Error


   Two. Some other recommendations:

1. Standardization of the name of the unified
The use of camel or underline format can be, uniform specification on the line. However, it is generally better to unify lowercase and underline at present. such as: User_id,user_name,user_age and so on.

2. Clear semantics, follow common abbreviations
The name of the field is best to reflect the type of the field, following some commonly used abbreviations, such as: User_name, Task_desc, DATE_STR, etc.

3. Handling of NULL and empty fields
The processing of null and empty fields is also more prone to problems. NULL for uniform null values. In addition to the Boolean type, the remaining null values are uniformly expressed in null, and the client guarantees that null for each field can be handled normally.

4. Each action is as consistent as possible with the crud operation principle.

5. Set default null values for different types
In addition to NULL, try to set the field "Default", such as the number is 0, the string is an empty string "", the array is an empty array [], the object is an empty object {}, which can avoid the client to handle the exception caused by null values.
Specific to the business, the front and back end of the convention depends on.
For example, a value of type bool is unified into numbers 0 and 1. The time-date type enforces only standard GMT/UTC timestamps, which are then displayed by the respective clients as they are processed according to their time zone and display requirements.

6. The full URL
The data in the API will also have a URL type, in general, such as the user's avatar, a variety of pictures, audio and other resources, are in the form of URL links returned.
Return the URL must be "complete", mainly refers to do not forget the URL inside the protocol part. It should be http://www.abc.com/1.jpg.

7. REST Security
You can use native HTTP Basic authentication, and you can also consider ways to meet more enterprise security requirements by supporting forms validation, LTPA validation, and Open ID validation.

8. Try to deploy the API under a dedicated domain name. For example: https://api.example.com.

9. The data format returned by the API should be used as much as possible to avoid using XML.

10. Return the correct HTTP response code, and redefine a set of business error codes to differentiate HTTP status codes.

11. Perfect documentation, it is best to automatically generate online API documentation so that the document can be kept up-to-date.
There are many attacks that automatically generate API documentation, for example: Swaggerui.

WEB API design experience and summary

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.