Six-step implementation of the rest-style API

Source: Internet
Author: User
Tags response code

The rest author thinks that the biggest achievement is not the enterprise application, but the Web, which is the endless Internet web world. The web can be such a big achievement, it deserves our research. So the rest author studied the web carefully, according to some key features of the world of the Web, and presented a style that we should follow when implementing enterprise applications, that is, restful.

Rest-style APIs can give us a lot of benefits, such as simplicity, unity, performance, scalability, and more. Unfortunately, when it comes to rest, there are always some of the key features of rest that are not implemented, such as statelessness, which exists in the two projects I've done and another project I know of. In fact, it's not that easy to get stateless in Java, because that means abandoning the session of the servlet. In addition, some of the rest's other features are implemented differently in each project.

Next, I'll list some of the key steps I think you can take to implement the rest-style API:

1. All things are resources (Resource)

All objects that are to be manipulated by the API are resources only. Whether it exists or not, it is abstract. All resources will have a constant identity (ID) and no API action on the resource should change the identity of the resource. Resources are related to other resources, and resource-to-resource relationships are referenced by resource identities. The operation of the resources should be complete, such as the acquisition of resources should be a complete resource object (according to the characteristics of the enterprise reference some exceptions, will be mentioned later).

In fact, the above is entirely based on the characteristics of the Internet. In the Internet, a URL is a resource, the content of the resource is an HTML page, and no matter how the HTML content is changed, the URL will not change, the resource is connected by the connection between the HTML, and each time it gets the full HTML content.

If there is a blog system, then the resources can include: bloggers, each blogger is a resource, blog, each blog is a resource, blog and bloggers have links between, through the ID link, each blog will have a reply, reply is also considered a resource, but it is affiliated with the blog, You can think of the reply as a sub-resource of the blog (you can also think that the blog is blogger's child resources, how the abstraction depends on the specific application, not discussed here).

This step is usually not difficult to achieve, because it is similar to the object concept in ORM, implementation, if using a framework such as hibernate, the changes should be very small.

2. Standardize the operation of resources, preferably including crud

Crud refers to creating (create), reading (read), updating (update), deleting (delete)

It is not always possible to manipulate a resource with only crud, and the crud does not even have to look for operations. But this does not hinder our understanding of rest, and the requirement of rest is that the operation of resources should be uniform, regardless of which type of resource is being manipulated, and the API should be consistent. So when the client calling the API knows about a resource, it does not need to learn what to do with the resource, because the operations are consistent for all resources, they should support crud operations, and some other operations, such as list (to find, or list all resources), Merge (partially update the resource, which should be the only API that does not manipulate all content of the resource).

This is the same as the Web, HTTP only Get,put,post,head and so on a few unified requests (see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html).

To achieve a few simple operations is not difficult, difficult in these few simple operations can not support the entire system requirements. But think about it, the Internet is complex enough, or not successful, and the fish and bear paw can not be both. Sometimes the server side does not have to implement everything, you can give some logic to the client to do. For example, the rest display is completely handed over to the client, and the server is just storing the data, whether the client is a Web page, a mobile app, or another enterprise application. A variety of clients come in, they will have a variety of requirements, the server can not be satisfied, only the client using a unified API to combine to achieve their own needs.

3. Use of canonical URLs

Well, the operation of the resource is unified, but the client still knows how to trigger a specific operation on the resource. Rest uses URL specifications to ensure this uniformity.

Create and save a blog:

[Plain]View Plaincopy
    1. Post/blog/save


This request needs to return the saved results of the blog, including the blog's Identity (ID). Get an already saved blog and update it:

[Plain]View Plaincopy
    1. get/blog/get/345
    2. Update it
    3. post/blog/update/345

The logo of this blog is 345. Get a reply from a blog:

[Plain]View Plaincopy
    1. get/blog/get/345/reply/456

The usual way to treat sub-resources is to look down at the same level as this example. We can also have other methods, such as remove to delete, merge for partial updates, list to find.

There are three ways to pass parameters to API operations:

The first is to pass the address of the URL, as in the previous example, put the logo in the URL;

The second is through the parameters of the URL, for example, for a lookup request, you can put the search filter conditions in the parameters:

[Plain] view plaincopy

  1. Get/blog/list?name=azure: Communication with Instanceinputendpoint direct and specified instance

The third is put or POST request, put the content in the HTTP body inside. This is usually the content of the blog.

Some of the previous requests in our example are get, some of which are post, in fact this is principled. Typically, operations that do not change the contents of a resource are useful get, such as acquiring resources, finding resources, and using post for changes to resources, such as saving resources.

If you want to do better, we should take a closer look at the HTTP request method, directly map the HTTP method and the operation to be done. For example, I like to think that a GET request is to get a resource (get), the Put method is to update the entire content (save,update, I think these two do not need to distinguish), the Post method is to update part of the content (merge), delete method is to delete the resource (remove). If so, the URL of the request can be simplified:

[Plain]View Plaincopy
    1. Put/blog//Create and save a new blog
    2. get/blog/345//Get blog 345 content
    3. put/blog/345//Update blog 345
    4. get/blog/345/reply/456//Get blog 345 's reply 456
    5. post/blog/345//Update some content of blog 345
    6. delete/blog/345//Delete blog 345


Of course, for the list operation, here is not enough, or need to make some difference at the URL level.

For the merge operation, there are a lot of people who think it is unnecessary, rest should not provide this API, but I think it is useful in some cases. For example, a resource object, its content is constantly expanding, how to let the old client after the content expansion can continue to use it? If we ask all update requests to put everything in the body of the request, it is not so good for the client, but if we allow the merge request, the client can completely ignore the newly added fields and just put the fields that they know in the request content.

4. Multiple representations of resources

I don't think this step is necessary.

In rest, the contents of a resource are usually returned directly to the client as a JSON or XML. Multi-resource representations of resources refer to the ability of a resource to support the client's request and return the appropriate format to clients. The server should follow the Accept property in the request HTTP header to determine the return format. For example, for an AJAX request, the Accept header is Application/json, the server returns the JSON format, and for Android requests, the Accept header is Application/xhtml+xml, which returns the XML format.

I don't think this step is necessary because at least in the early stages of the project, we should all only support one format. Multiple representations of resources give us a way to handle multiple request formats, but we don't need to support them from the start.

5. Further reasonable use of HTTP

We have already applied some of the HTTP things, such as the request method, the Accept header. In fact we can use more.

HTTP supports client-side caching, with cache-control,expires,last-modified three header fields in the HTTP response, allowing the browser to cache resources for a period of time. Rest can also use these headers to tell the client that there is no need to request resources again for a certain amount of time. This is a great benefit for improving performance. For more HTTP header information, refer to Http://en.wikipedia.org/wiki/List_of_HTTP_header_fields.

The rest request will be faulted, and the HTTP request will be faulted. We can directly use HTTP's response code to tell the client that the rest requested something wrong. For example, 500, tell the client, the server error, 401 to tell the client needs to attach security authentication information, need to log on the system, 404 tell the requested resource does not exist, and so on. For more HTTP response codes, refer to http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html. In the actual business, those HTTP response code must not meet all the requirements, appropriate in the response body with more detailed error information is also necessary.

There are many other, in short, can use on the use, no more than the invention of the wheel.

6. Stateless implementation of the request

Rest is stateless. There should be no dependency between rest requests, and it is not necessary to call another request before calling a request. There should not be a session in rest, especially the rest request should not save the information in sesssion for use in subsequent calls. Even if security authentication is included, the client should not need to log in early and then save the permission information in the session, and the subsequent request is invoked with the same session.

The way to implement stateless is to include all information in the current request, including validation information. HTTP is stateless, HTTP has a authorization header, HTTP requirements are in each request to put the authentication information inside, the server every time before processing the request to verify the information. For security, we can provide a rest API that generates tokens, which the client calls to generate tokens (a username/password can be attached to generate tokens). This token is placed in the authentication header in all subsequent requests.

The biggest benefit of achieving stateless is the ability to easily extend the server, or scalability. Otherwise, we either bind the session to a specific server or use a shared space to store the session. With stateless, we can increase the number of servers at will, and no impact on the current user.

Keywords: rest, resful, implementing rest

Six-step implementation of the rest-style API

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.