REST itself is a design style rather than a standard. REST talks about a very important thing, how to use Web standards correctly, such as HTTP and URIs. The best way to learn about REST is to think about and understand the Web and how it works . If you design an application that conforms to the rest principles, these restful rest services can be referred to as "RESTful Web service" or "restful web api ". The end of "-ful" emphasizes that their design fits perfectly with the recommendations in the REST paper.
Best practices: Better design your REST API
The REST API Design has many of its own unique skills to be aware of in detail, and is more demanding than traditional APIs for developers in their architectural design capabilities. This article analyzes and interprets the issues that REST API design should be aware of and how to address them in order to improve ease-of-use and efficiency through a detailed narrative and a series of examples, from the overall structure to the local details.
Because REST can reduce the complexity of development, improve the scalability of the system, enhance the scalability of the system, simplify the integration between the application system, so the majority of developers love, at the same time, the industry has been widely supported. Many of the company's products, such as Ibm,google, provide rest APIs to developers, while a large number of open source projects and cloud computing services provide REST API interfaces.
Recently, the development of some new products has almost completely abandoned the traditional JSP-like technology, instead of using the rest-style architecture design, that is, all business logic on the server side is exposed to the client in the form of rest API, all browser user interface uses WIDGET,AJAX,HT ML5 and other technologies, using HTTP to interact with the background directly.
So how do we better design our interfaces to improve the usability, ease of use, maintainability and scalability of our APIs as the REST API explodes today? This article explores best practices for REST API design in the following ways:
How to plan resource identity structures and URI patterns
How to provide content negotiation based on application scenarios
How to use the HTTP response code correctly
How to handle caching and concurrent requests
How to leverage data redundancy and link elements
Prerequisite
If you have the following knowledge and experience, will help you to read and understand the content of this article
Back to top of page
Understanding and using Content negotiation
While our developers are sending a REST API request, depending on the scenario, a different return form may be expected for the same resource.
For example, I want the content of the same resource to be returned in different languages, depending on the user's client language. For example, when I use Java programming, I want to get the result of the ATOM format, and when I use JavaScript programming, I want to get the return result in Json format.
Therefore, when designing the REST API, we should provide complete content negotiation capabilities.
Using URL parameters for content negotiation
The most easily imagined nature is controlled by URL parameters, we often see the shape of the/flight number/entry? Format=json such a URL. The advantage of this approach is that it is simple and flexible, and you can combine your output format with any URL parameter.
Here is an example of an API from IBM DeveloperWorks that attempts to request the API, and you can see how the collection supports different output format requests.
Listing 3. IBM DeveloperWorks's API for file services tag cloud
REST API request, requires return XML format data: GET https://www.ibm.com/developerworks/mydeveloperworks/files/form/anonymous/api/ Tags/feed?format=xml &SCOPE=DOCUMENT&PAGESIZE=30&SK=CLOUD&SO=DSC REST API request, request to return JSON Format data: GET https://www.ibm.com/developerworks/mydeveloperworks/files/form/anonymous/api/tags/feed?format= JSON &SCOPE=DOCUMENT&PAGESIZE=30&SK=CLOUD&SO=DSC
Content negotiation using the Accept header
The use of URL parameters, simple and flexible, but also resulting in the design of arbitrary and non-standard. Also, too many parameters can cause the URL to become less readable and, worse, cause the URL to be too long to exceed the specification and the API request cannot be executed.
A more standard way to negotiate content is to use HTTP headers. We usually use accept to set the content format of the returned results we accept, set the character set with Accept-charset, set the data transfer format with accept-encoding, and set the language with Accept-language.
Using URI mode for content negotiation
There is also a pattern, that is, the negotiation settings directly as part of the URI, the different returns as different resources, such as/flight number/json to return the results in JSON format, with the/flight number/atom to return the results in atom format.
Back to top of page
Correct use of HTTP response code
As the designer of the API, it is a critical step to communicate the results of the API execution and the reasons for failure in a clear and concise manner to the client. We can really describe success in the corresponding content of HTTP, if something goes wrong, however, this means that the user needs to parse the content before they know the execution result and the cause of the error. Therefore, the HTTP response code ensures that the client learns the results of the API operation in the first time and takes the appropriate action in the most efficient way possible. The following table lists the more commonly used response codes.
Table 1. Common HTTP Response code meaning
HTTP Response Code |
Code meaning |
200 |
Created, the request succeeds, and the server has created a new resource. |
201 |
Show only app instances in the warning state |
301 |
Redirect, the requested page has been permanently moved to the new location. When the server returns this response, the requestor is automatically forwarded to the new location. |
302 |
Redirect, the requested Web page is temporarily moved to a new location, but the requester should continue to use the original location for future requests. 302 automatically transfers the requestor to a different temporary location. |
304 |
Not modified, the requested Web page has not been modified since the last request. When the server returns this response, the Web page content is not returned. |
400 |
Error request, the server does not understand the syntax of the request. |
401 |
is not authorized, the request for authentication is requested. |
403 |
Disabled, the server rejects the request. |
404 |
Not found, the server could not find the requested Web page. |
405 |
method is disabled to disable the method specified in the request. |
406 |
Does not accept that the requested content attribute cannot be used in response to the requested Web page. |
408 |
The request timed out and the server timed out while waiting for the request. |
410 |
deleted, and the server returns this response if the requested resource has been permanently deleted. |
412 |
The precondition is not met and the server does not meet one of the prerequisites set by the requestor in the request. |
415 |
Unsupported media type, the requested format is not supported by the requested page. |
500 |
Internal server error. |
Back to top of page
Handling caching and concurrency using HTTP headers
Caching and concurrency processing have always been an important part of the design of large software systems.
Using HTTP headers for cache processing
In the rest of the architecture, we need a good caching mechanism in addition to the data exchange in the background, for the rest API requests are at the remote end of the HTTP launch this feature, but also for the network cache for more consideration. Improve the efficiency of REST API usage by reducing HTTP response content, avoiding unnecessary HTTP connections, and more.
In the HTTP header, there are several fields that can be used for caching processing. More commonly, there are cache control and conditional requests.
Cache control:
Cache control typically requires a client, and the cache server/proxy server works with the business Server.
There are "Cache-control" fields in the HTTP header to control how the cache is used, and the common values are private, No-cache, Max-age, Must-revalidate, and so on. For example, when you set the max-age=600 for the returned data, it will not cause the background data to be re-requested when the user requests again for 30 seconds.
Alternatively, you can specify the content expiration by using the "Expires" field, which does not cause the daemon to re-request the data before this time.
Shows how Max-age works.
Figure 2. A simple example of how cache control works
Conditional requests with electronic tags:
Most of the time, the data content may not be changed in hours or even days, and this time, according to the request interval to control the cache, can not meet the needs of the system. By supporting conditional requests with electronic tags, you can help us to solve this problem.
When the user requests the data content, the system returns the data at the same time, in the HTTP header, the last-modified is returned based on the last modification time of the server content, or the electronic label ETag is generated based on the server content. When the user requests the data again, it is possible to use the If-modified-since or If-none-match header information in the HTTP request to pass the timestamp or electronic tag from the last request to the server. When a REST request for a conditional request HTTP header is received, our program needs to compare the received timestamp or electronic tag with the current content, it is easy to know whether the user requested the data content has been modified during this time, and based on the comparison results returned to the user's latest content, or with HTTP Response Code 304 informs the user that the content has not changed.
Here is an example of an API from IBM DeveloperWorks that attempts to request the API and you can see that the API returns electronic tags and cache processing information in the HTTP header.
Listing 4. IBM developerWorks File Services API with electronic tags
REST API Request: GET https://www.ibm.com/developerworks/mydeveloperworks/form/anonymous/api/communitylibrary /7e2e8015-bf72-43b6-bacd-36565b67febc/document /ddc0ef4e-224e-449c-bb2c-f919fafb17d2 /entry?acls=true &includerecommendation=true &includetags=false&includelibraryinfo=true&format=xml
Using HTTP headers for concurrent processing
We mentioned the use of conditional requests to control caching, but we can also use conditional requests for concurrent processing.
For example, when user Alice and Bob get a document through REST. Bob modifies the document with a PUT after reading the document, and in a few minutes Alice has just modified the document, so Bob inadvertently overwrites Alice's changes without knowing.
By supporting conditional requests in a write operation, we can better handle concurrent modifications. The user makes the modification request, uses the If-not-modified-since or the If-match header information in the HTTP request, passes the timestamp or the electronic tag which obtains the data to the server; Our program can be known by comparing the current contents of the server. Whether this modification request was made for the current content. When the server discovers that the content has been modified by another user, it does not execute the modification request and returns the HTTP response code 412 (which does not meet the prerequisites) to the user.
Shows how concurrent processing using conditional requests and electronic tags works
Figure 3. Simple example of concurrency handling when conditional requests are supported
Back to top of page
Better use of data redundancy and link elements
In the ATOM document, we use various data elements to convey information. There is a class of elements called links that can be used for further developer access. Typically, we provide links to edit current resources, access links to current resources, and so on. By using this type of link element more flexibly and providing the necessary data redundancy, we can greatly simplify the developer's programming logic and improve the efficiency of REST API usage.
Back to top of page
More details and tips to keep in mind
In addition to the above mentioned aspects, there are a lot of details and techniques to help us better design the REST API:
Batch update:
When users need to update multiple resources, do you plan to let developers send HTTP requests to update one after the other? You might consider allowing the client to create or update multiple resources at the same time when designing the API.
REST Security:
In addition to using native HTTP Basic authentication, you can also consider ways to meet more enterprise security requirements by supporting forms validation, LTPA validation, and Open ID validation.
Document Services:
Is the API constantly being updated so that clients are struggling to connect to different versions of the service? Try to standardize your API definition into an XML document so that it is easy for clients to understand what functionality the current service can provide and how to use it.
You can also learn more about this by reading other documents, and this article will not be able to get all the details and tricks one by one exhaustive.
Back to top of page
Summarize
Through the above examples of experience and techniques, we learned how best practices can be used to better design REST APIs. We note that since the REST API is primarily for Web applications, and a lot of calls come from browser scripting, there are a number of unique tips to be aware of in detail. In addition, because REST is increasingly becoming a principle and framework for system design, it also requires our program developers to think in terms of the architect's perspective and height when designing the API. I hope this article can help you open the REST API design ideas, explore and summarize more skills, with the vast number of developers to share.
REST API (from IBM)