Design a good restful api_spring

Source: Internet
Author: User
Tags oauth representational state transfer
It's written in front of you.

Look at the blog directory, from the last update this series of posts has been two months, not because do not want to continue to write blog, because the middle of this period of time updated several other series of articles on the temporary stop, now has been told about almost, also continue to make time to update the "spring+springmvc+ Mybatis+easyui Integration "this series.


Also see GitHub on someone to push more tutorials, this really is not thought, also thank you for your affirmation and support.

Because the article about code optimization and data layer optimization in the integrated optimization article occupies a larger space, resulting in the omission of several original plans to be updated in the Integrated optimization article, the integration of restful and caching functions has not been done, this time will be added in. Understanding RESTful

REST (representational state Transfer), a Chinese translation called "Presentation status Transfer", first appeared in the 2000 Roy fielding doctoral thesis, Roy Fielding is one of the main writers of the HTTP specification. "The purpose of my article is to understand and evaluate the architecture design of web-based applications based on the principles of architecture, and to get a powerful, good performance and suitable communication architecture," he said in his paper. Rest refers to a set of architectural constraints and principles. "If a schema conforms to rest constraints and principles, we call it the RESTful architecture, and rest does not actually create new technologies, components, or services, and in my understanding it should be more of an idea, an idea that leverages the existing features and capabilities of the web, Better interpret and embody some of the guidelines and constraints in existing Web standards.

After reading this theoretical introduction may not make you have any ideas about restful, even just a sweep, then through the actual case to explain it.

There are articles in the SSM project that manage this module, the article List page deletes the service side API of the article request
Http://ssm-demo.hanshuai.xin/article/delete.do,
This URL is not restful-style API, slightly modified, url into:
HTTP://SSM-DEMO.HANSHUAI.XIN/ARTICLE/DELETE/12,
This is not the restful style.

First of all, these two URLs are not RESTful APIs, because these two URLs have delete action instructions, RESTful API is a resource-oriented architecture, so its URL should be a resource, and should not contain any actions, The specific type of operation for the resource should be represented by an HTTP verb, not a verb that exists in the URL, and delete is a verb and therefore does not conform to the feature, and the corresponding restful API for the deletion of the article should be:
[DELETE] HTTP://SSM-DEMO.HANSHUAI.XIN/ARTICLES/12 common restful misunderstanding

Again, the first contact with the restful can be a misunderstanding: some pseudo static URLs, such as HTTP://SSM-DEMO.HANSHUAI.XIN/CONTENTS/12, we can access the URL through the browser to obtain information, But that doesn't mean it's the restful API. URLs containing querystring are not RESTful APIs, such as Http://ssm-demo.hanshuai.xin/articles/?page=1&rows=10,RESTful APIs can contain QueryString. HTTP + json = RESTful api,http and JSON are not equal to restful,restful features richer and cannot equate RESTful simply with HTTP and JSON. Design principles for good restful APIs

The specific implementation of RESTful API design can be viewed in my GitHub, the following is some design principles of collation: Basic principle: URI should deploy API under the dedicated domain name: ssm-demo.hanshuai.xin; Try not to capitalize in the URL; Verbs should not appear in URIs, verbs should be expressed using the HTTP method but if not, you can use verbs, for example: Search does not have corresponding HTTP method, you can use search in the path, more intuitive; A noun in a URI represents a collection of resources, using the plural form; URIs can contain QueryString and avoid layers that are too deep. Basic principle two: HTTP verbs

For specific operational types of resources, represented by the HTTP verb, the commonly used HTTP verbs have the following five: get: Fetching resources from the server (one or more items). POST: Create a new resource on the server. Put: Updates the resource on the server (the client provides the complete resource after the change). PATCH: Updating resources on the server (client provides changed properties). Delete: Deletes a resource from the server.

There are two more infrequently used HTTP verbs: Head: Gets the metadata for the resource. OPTIONS: Gets information about which attributes of a resource can be changed by the client.

Example:

Article Management module:

1. [POST]   Http://ssm-demo.hanshuai.xin/articles   //Add
2. [Get]    http://ssm-demo.hanshuai.xin/articles?page=1&rows=10//List Query
3. [Put]    HTTP://SSM-DEMO.HANSHUAI.XIN/ARTICLES/12//Modification
4. [Delete] HTTP://SSM-DEMO.HANSHUAI.XIN/ARTICLES/12//delete
Basic Principle III: Status code (state codes)

The status code and hint information that the server will return to the client after the request is processed.

Common status code (status code can be designed, only the developer agreed to a good specification): 200:success, request success; 401:unauthorized, no authority; 403:forbidden, forbidden to visit; 410:gone, no such resources; 500:internal Server error.
... Principle Four: Error handling

If the server has an error or the resource is unreachable, you should return an error message to the user. Basic principle Five: server-side Data return

The return result of the backend is best used in JSON format. Basic Principle VI: The API for the versioning specification should contain version information, and in the RESTful API, the simplest way to include versions is to place version information in URLs, such as:

[Get]    Http://ssm-demo.hanshuai.xin/v1/articles?page=1&rows=10 
[put]    
Alternatively, use the accept in the HTTP header to pass version information.

The SSM project is simpler, so the version information is not added at the moment.

The following is a reference to the content of a blogger on the security principle of collation: Security principles One: Authentication and permission

Authentication refers to the user authentication, permission refers to the authority mechanism, these two points is makes the RESTful API formidable, the flexibility and the security basic safeguard.

The common authentication mechanism is the basic Auth and Oauth,restful API development, unless the API is very simple, and no potential security issues, otherwise, the authentication mechanism must be implemented and applied to the API. Basic Auth is very simple, many frameworks are integrated with the implementation of basic Auth, write one can be quickly done, OAuth is now the standard of enterprise-class services, its relevant open source implementation is very rich (more). Safety principle Two: CORS

Cors Cross-origin resource sharing, in the RESTful API development, is mainly for JS service, solve the JavaScript call RESTful API when the Cross-domain problem.

Because of the inherent security mechanism, JS's Cross-domain request cannot be successfully responded to by the server. Now the front-end separation increasingly become the mainstream of web development under the trend, the background gradually tend to refer to the provision of API services for the clients to provide data and related operations, and the development of the site all to the front end, Web sites and API services are rarely deployed on the same server and use the same port, JS Universal Request when the development of RESTful API, usually take into account the implementation of the Cors function, so that JS can normally use the API.

At present, the mainstream web development language has a lot of excellent implementation of cors open Source Library, we in the development of RESTful API, we should pay attention to the realization of cors function, directly with the existing wheel to use. Security principle Three: SSL

HTTP is changed to HTTPS to enhance security authentication. Summarize

The above made a few simple summary, may not be very accurate, if there is a mistake, I hope to be able to point out that I will promptly revise, thank you.

Starting with my personal blog, new project demo address: PERFECT-SSM.

If there is a problem or some good ideas, please leave me a message, but also thank me to point out that the project has problems in the friend, the specific function of the implementation and code logic will be introduced in the post.

If you want to continue to understand the project you can view the entire series of articles Spring+springmvc+mybatis+easyui the integration series, you can also go to my GitHub warehouse or open source China code warehouse to view source and project documentation.

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.