(Transfer) Restful API Design Ideas and Practice

http://www.jianshu.com/p/265397f812d4

I remember when I first wrote an APP, I didn't know anything about REST, and I didn't know much about Web Services. When another classmate and I were discussing which protocol to use to interact with each other, after thorough research (actually, searching for a search engine...), we agreed that HTTP itself consumes so much bandwidth, so Many Web Services (when SOAP was still in power) were still based on HTTP, so how much bandwidth was wasted. In the end, we unanimously decided to use Socket for communication. It was not easy to think about it at that time. We just built a communication protocol on Socket and developed it to the second version.

Today, with the popularity of mobile applications and the separation of front-end and back-end, RESTful API is very popular, but because it is a relatively vague and broad concept, everyone has a different understanding of it. I think that when we select a technology, we should first consider the needs of our own system on the basis of our own technology accumulation and reference to the existing industry best practices, and think about the impact of "selecting a certain technology" on the development and development of the system. What are the advantages and disadvantages of maintenance, not what others use and what others use. Moreover, there is currently no recognized industry best practice for RESTful API design. Therefore, when developers design an API system, they should tailor it according to their own situation. Never say "I copied the open API of a certain company." "Enough. This article will summarize some knowledge and experience of RESTful API design based on my experience using REST, and encourage myself. This article will not discuss security issues such as Oauth.

First clarify some concepts:
REST (Representational State Transfer)
defines a design style for Web-based data interaction.
RESTful
An API that conforms to the REST style can be called a RESTful API. Note that the RESTful API design method described in this article will be based on HTTP and JSON implementations, but neither HTTP nor JSON is a REST standard. REST is just style, not standard.
Verbs and RPC
searched [RESTful API Design] in WeChat, and many articles came out about how to use verbs in RESTful Uri, etc. Except for some of these people who copied the articles, others actually confused REST With the concept of RPC, REST emphasizes resources, and RPC emphasizes actions, so the Uri composition of REST is a noun, and RPC is mostly a verb phrase. However, they are not two completely unrelated things. The implementation in this article will refer to some of the design ideas of JSON-RPC.
Web Service
is an older concept with a set of its theories, but I prefer to understand it as any web-based service.
Design methods and principles:
1. Use the HTTP method:
The HTTP1.1 specification defines 8 verbs, but HTTP as a specification is not strictly followed. In most cases, POST can be completed except for any kind of request. Therefore, many API designs now only use GET and POST to call APIs. In this case, the general practice is to use GET to obtain resources, and other behaviors are completed by POST, and in order to distinguish different behaviors , often adding verbs to the Uri of the API, such as the following API pushed by Baidu:

[ POST ] /rest/3.0/app/del_tag
function
Delete an existing tag

parameter The
parameter name type must be limited to describe
the tag string is 1~128 bytes , but not the 'default' tag name
Return value
Name type description
tag string Tag name
result number Status 0: Created successfully; 1: Created
A clearer API design may use GET POST PUT DELETE four methods to represent four actions such as "query, add, update, delete" , which is conceptually compliant with the HTTP specification, such as Google's following API:

Request
DELETE https://www.googleapis.com/bigquery/v2/projects//datasets/?key={YOUR_API_KEY}

Response
404 Not Found

– Show headers –

Not Found
In my opinion, there is no absolute good or bad. If you use the first method, as long as the semantics of Uri are clear, it is not much different from using the second method.

2. Uri format:
Uri identifies a resource in REST, but in the specific API design, it is often impossible to fully map the resource. The design in this article will refer to the more popular Uri design, roughly as follows :

The root of Uri (root, /) should be able to identify that this is a RESTful API to distinguish it from other resources that may exist in the same directory.
Immediately after the root of the Uri, the version number of the current API should be identified.
If the method is POST or PUT, try to avoid using URL-encoded parameters, and try to keep the Uri as clean as possible.
If the method is DELETE, the Uri should fully identify the object or collection of objects that need to be deleted, avoid using other parameters in the DELETE request, because some servers may discard the content sent with the DELETE.
Here again take the industry benchmark Google's open API as an example:

POST https://www.googleapis.com/books/v1/mylibrary/annotations

PUT https://www.googleapis.com/bigquery/v2/projects/p1/datasets /p2

DELETE https://www.googleapis.com/bigquery/v2/projects/{project-parameter}/datasets/{datasets-parameter}
3. Most implementations of fixed return code
REST are an HTTP based, then Naturally, it is necessary to deal with the return code. Unfortunately, the definition of the HTTP return code seems to be very arbitrary, and many error messages are unclear, and in actual development, API users need to deal with link problems (such as timeouts, etc. ), a wide variety of HTTP return codes, and the actual return content, which is extremely cumbersome. More seriously, most of these return codes ultimately depend on the specific implementation of the server-side developer, and this seemingly agreed-upon thing may have very different meanings in the eyes of the client-side and server-side developers respectively.

So starting from the requirements, the reason why we need to use the return code when using the RESTful API is roughly as follows: after the client calls an API, the received feedback must be able to identify whether the call is successful, if not, The client needs to get the reason for the failure. We can make a small agreement in API design to perfectly meet the above requirements.

After successfully receiving the client's request, the server always returns 200, and the specific success or not and further information are put into the returned content.

In this scenario, if there is a problem with the link or a server error (the return code is not equal to 200), the client can easily catch this error. If the link is ok, then the error is in the feedback content obtained. will be described in detail.

4. Fixed return structure
Now more and more API designs will use JSON to transmit data, and the design in this article will also use JSON. JSON-RPC is a well-known and concise RPC specification based on JSON. This article will draw on the design of JSON-RPC's response object.

The basic idea behind the design of the server response object in JSON-RPC is that as long as the call is successful, the server must respond with data (as discussed in #3), and the format of the response data should be consistent in all cases, The response format of JSON-RPC is designed like this:

{"jsonrpc": "2.0", "result": 19, "id": 1}

{
    "jsonrpc": "2.0",
    "error":
        {
            "code": -32600,
            "message": "Invalid Request"
        },
    "id":




result
This member is REQUIRED on success.

This member MUST NOT exist if there was an error invoking the method.

The value of this member is determined by the method invoked on the Server.

error
This member is REQUIRED on error.
This member MUST NOT exist if there was no error triggered during invocation.

The value for this member MUST be an Object as defined in section 5.1.

id
This member is REQUIRED.

It MUST be the same as the value of the id member in the Request Object.

If there was an error in detecting the id in the Request object (eg Parse error/Invalid Request), it MUST be Null.
Since the goal of JSON-RPC is to establish a common specification, the design of the response format is still a bit complicated, we can just take Among them, for the design of the error object, all returned formats must be like this:

{
    "code": -32600,
    "message": "Invalid Request",
    "data":{ }
}
This format design is also common in the open APIs of many large companies, such as Google, which is an industry benchmark, when calling The error data obtained after an API of the Google Open Platform is as follows, and the design idea is the same as the idea of ​​the return format discussed in this article.

{"error": {
    "errors": [
            {
                "domain": "global",
                "reason": "required",
                "message": "Login Required",
                "locationType": "header",
                "location": " Authorization"
            }
        ],
    "code": 401,
    "message":



The Uri of all APIs is an HTTP-based noun phrase used to represent a resource.
The Uri format is as described in the text.
Use the four methods of GET POST PUT DELETE to represent "query, add, update, delete" for resources.
After the server receives the client's request, it returns 200 uniformly. If the return code obtained by the client is not 200, it means that there is a problem in a certain link on the link.
All the response formats of the server are:

{   
     "code": -32600,
     "message": "Invalid Request",
     "data": { }
}
Their meanings respectively represent:

code is 0 means the call is successful, others will be customized Error code;
message indicates the detailed error information when the API call fails, this information can be directly presented to the user by the client, otherwise it is empty;
data indicates the data returned by the server, the specific format is customized by the server, and the API calls error is empty

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327008013&siteId=291194637