A discussion on service-side rest and soap

Source: Internet
Author: User
Tags representational state transfer what interface

About REST

Before we begin our formal discussion, let's take a quick look at the definition of rest.

REST (representational state Transfer) is a noun presented by Roy Fielding describing the architectural style of an interconnected system. Why is it called rest? The web is essentially composed of a variety of resources, and the resource is uniquely identified by the URI. The browser (or any other browser-like application) will show a representation of the resource, or a performance state. If a user directs a link to another resource on the page, the resource is accessed and its status is displayed. This means that the client application has a state transition, which is called rest, depending on the state of each resource's performance. As for rest itself, this article is no longer discussed here, and readers can refer to other articles on Developerworks for rest. The focus of this article is to help readers understand the features and benefits of the rest architecture style more deeply by comparing rest with soap Web services.

Application Scenario Introduction (Online user management)

This article will use a scenario to compare the two with different implementations based on rest and soap Web services. The business logic of this scenario is as simple and easy to understand as possible to help put our focus on the contrast between rest and soap Web service technology.

Requirements Description

This is an online user management module, responsible for user information creation, modification, deletion, query. The user's information mainly includes:

    • User name (unique flag for users in the system)
    • Title
    • Company
    • EMAIL
    • Describe

Requirements use case diagrams such as:

, Client 1 (CLIENT1) and Client 2 (CLIENT2) have different permissions for information access, client 1 can perform all operations, and client 2 is only allowed to execute user queries (query user) and user list queries (query user lists). With this in mind, we'll talk about the rest Web service in contrast to the SOAP Web service security control. Below we will show you how to implement Web services using rest and SOAP schemas, respectively.

Implementing Web Services with rest

This section will implement the application based on the Restlet framework. Restlet provides a specific solution for Java developers who want to use the rest architecture to build applications. For more Restlet related content, this article does not do in-depth discussion, see the Reference Resources list.


We will design with Roa (resource-oriented Architecture, resource-oriented architecture) that follows the rest design principles.

What is ROA? To put it simply, Roa is a way to convert real-world problems into restful web services, which makes URIs, HTTP, and XML work the same way as other Web applications. When designing with Roa, we need to translate real application requirements into resources in Roa, basically following these steps:

    • Analyze data sets in your application requirements.
    • Map datasets to resources in Roa.
    • For each resource, name its URI.
    • Design their representations for each resource.
    • Use hypermedia links to express the links between resources.

Next we will follow the above steps to design the application case of this article.

The data set involved in online user management is user information, and if mapped to the ROA resource, it mainly consists of two types of resources: User and user list. The URI of the user resource is represented by Http://localhost:8182/v1/users/{username}, and the URI of the user list resource is represented by Http://localhost:8182/v1/users. Their representation are as follows, and they all use the XML representation shown in Listing 1 and listing 2.

Listing 1. User List Resource representation

<?xml version= "1.0" encoding= "UTF-8" standalone= "no"?><users>    <user>        <name>tester </name>        <link>http://localhost:8182/v1/users/tester</link>    </user>    < user>        <name>tester1</name>        <link>http://localhost:8182/v1/users/tester1</link >    </user></users>

Listing 2. User Resource representation

<?xml version= "1.0" encoding= "UTF-8" standalone= "no"?><user>    <name>tester</name>    <title>software engineer</title>    <company>IBM</company>    <email>[email Protected]</email>    <description>testing!</description></user>

The client <link>http://localhost:8182/v1/users/tester</link> obtains a specific user Resource through the link information (for example:) provided by the user List Resource.

Restful Web Services Architecture

First, the overall architecture diagram of the Web service is implemented using the rest style, as shown in:

Next, we'll use Restlet to give the app a restful Web service implementation based on the architecture. In the following sections, we will give the core code snippets of the rest Web Service implementation. For a complete code listing, readers can download it from a list of resources.

Client implementation

The list gives the core implementation part of the client, which consists mainly of four parts: adding and Modifying user resources using HTTP put, using HTTP get to get a specific user resource, using HTTP Delete to delete user resources, using HTTP GET to get a list of user resources. These four parts also correspond to the four pairs of HTTP messages that are described in the schema diagram above. For a complete implementation of the Userresthelper class, please see the code sample attached to this article.

public class Userresthelper {//the root URI of our ROA implementation.    public static final String Application_uri = "HTTP://LOCALHOST:8182/V1";    Get the URI of user resource by user name.    private static string Getuseruri (string name) {return Application_uri + "/users/" + name;    }//get the URI of the user list resource.    private static String Getusersuri () {return Application_uri + "/users";    }//delete user resource from server by user name. Use the HTTP Delete method to delete user resources by URI public static void Deletefromserver (String name) {Response Response = new Clie        NT (protocol.http). Delete (Getuseruri (name));    ...... }    Put user resource to server.        Use the HTTP PUT method to add or modify user resources by URI public static void Puttoserver (user user) {//fill FORM using user data.        Form form = new form ();        Form.add ("User[title]", User.gettitle ());        Form.add ("User[company]", User.getcompany ()); Form.add ("User[email]", User.getemail());        Form.add ("user[description]", user.getdescription ()); Response putresponse = new Client (protocol.http). Put (Getuseruri (User.getname ()), form.getwebrepresentation        ());    ...... }    Output user resource to console.    public static void Printuser (String name) {Printuserbyuri (Getuseruri (name));    }//output user list resource to console. Use the HTTP GET method to display the user list resource by URI public static void Printuserlist () {Response getResponse = new Client (Protocol.        HTTP). Get (Getusersuri ());            if (Getresponse.getstatus (). Issuccess ()) {domrepresentation result = Getresponse.getentityasdom ();            The following code line would explore this XML document and output//each user resource to console. ...... }        else {System.out.println ("Unexpected status:" + Getresponse.getstatus ());    }}//output user resource to console. Using the HTTP GET method to display user resources through URIs private static void priNtuserbyuri (String uri) {Response getResponse = new Client (protocol.http). Get (URI);            if (Getresponse.getstatus (). Issuccess ()) {domrepresentation result = Getresponse.getentityasdom ();            The following code line would explore this XML document and output//current user resource to console. ...... }        else {System.out.println ("Unexpected status:" + Getresponse.getstatus ()); }    }}
Server-side implementation

The list gives the server-side implementation of the User resource Class (USERRESOURC), whose core function is to respond to HTTP GET/PUT/DELETE requests for user resources. These request response logic corresponds to the HTTP request for the user resource class in the Userresthelper class.

public class Userresource extends Resource {private User _user;    Private String _username;        Public Userresource (context context, request request, Response Response) {//constructor are here.    ...... }        Response HTTP Delete request logical public void DELETE () {//Remove the user from container.        GetContainer (). Remove (_username);    GetResponse (). SetStatus (STATUS.SUCCESS_OK);    }//this method is called by Handleget.        Public representation Getrepresentation (variant variant) {representation result = NULL;            if (Variant.getmediatype (). Equals (Mediatype.text_xml)) {Document doc = createdocument (this._user);        result = new Domrepresentation (Mediatype.text_xml, doc);    } return result;    }//responds to HTTP PUT request logic.            public void put (representation entity) {if (getUser () = = null) {//the user doesn ' t exist, create it            SetUser (New User ()); GetUser (). SetName (This._username);            GetResponse (). SetStatus (status.success_created);        } else {getResponse (). SetStatus (status.success_no_content);        }//parse the entity as a Web form.        Form form = new form (entity);        GetUser (). Settitle (Form.getfirstvalue ("User[title]"));        GetUser (). Setcompany (Form.getfirstvalue ("User[company]"));        GetUser (). Setemail (Form.getfirstvalue ("User[email]"));        GetUser (). SetDescription (Form.getfirstvalue ("user[description]"));        Put the user to the container.    Getapplication (). GetContainer (). Put (_username, GetUser ());    }//responds to HTTP GET request logic.        public void Handleget () {super.handleget (); if (this._user! = null) {GetResponse (). Setentity (Getrepresentation (New Variant (mediatype.t            (Ext_xml)));        GetResponse (). SetStatus (STATUS.SUCCESS_OK);        } else {getResponse (). SetStatus (Status.client_error_not_found); }}//build XML document for User resource. Private document CreateDocument (user user) {//the following code line would create XML Document according to User I        Nfo.    ...... } The remaining methods here ...}

The Userresource class is an abstraction of the user resource class, including the creation and modification of the resource (Put method), the Read (Handleget method), and the deletion (delete method), the Userresource class instance that was created is hosted by the Restlet framework. All methods of manipulating resources are automatically recalled after the corresponding HTTP request arrives.

In addition, on the server side, also need to implement the resource class Userlistresource on behalf of the user list resource, its implementation is similar to Userresource, in response to the HTTP GET request, read all the user information in the current system, form as shown on the user list resource representation, and then return the result to the client. For specific implementations, please see the code sample attached to this article.

Implementing Web Services using SOAP

For SOAP implementations, this article is no longer specific to code-level implementations like rest. This section will primarily describe the technical nature of the SOAP Web service implementation through Uri,http and XML, laying the groundwork for the next rest Web service versus the SOAP Web service.

SOAP Web Service Architecture

Again, the overall architecture diagram for the SOAP implementation is given first, as shown in the following:

As you can see, the SOAP frame composition is significantly different than the rest architecture: All SOAP message sends use the HTTP POST method, and all SOAP message URIs are the same, which is the basic practice characteristic of soap-based Web services.

Get a list of user information

A SOAP-based client creates a SOAP XML document, as shown in the manifest, that obtains the user list information through the class RPC method.

Getuserlist SOAP Message

<?xml version= "1.0" encoding= "UTF-8" standalone= "no"? ><soap:envelope xmlns:soap= "/http/ schemas.xmlsoap.org/soap/envelope/">    <soap:Body>        <p:getuserlist xmlns:p="/http Www.exmaple.com "/>    </soap:Body></soap:Envelope>

The client will use the HTTP POST method to send the above SOAP message to Http://localhost:8182/v1/soap/servlet/messagerouter URI,SOAP Server to receive the HTTP POST request. By decoding the SOAP message to determine the need to call the Getuserlist method to complete the Web service call, return the following response:

Getuserlistresponse message

<?xml version= "1.0" encoding= "UTF-8" standalone= "no"? ><soap:envelope xmlns:soap= "/http/ schemas.xmlsoap.org/soap/envelope/">    <soap:Body>        <p:get  userlistresponse xmlns:p=" http ://www.exmaple.com ">        <Users>            <username>tester<username>            <username> Tester1<username> ...        </Users>        <p:getuserlistresponse >    </soap:Body></soap:Envelope>
Get a specific user information

Getuserbyname SOAP Message

<?xml version= "1.0" encoding= "UTF-8" standalone= "no"? ><soap:envelope xmlns:soap= "/http/ schemas.xmlsoap.org/soap/envelope/">    <soap:Body>        <p:getuserbyname xmlns:p="/http Www.exmaple.com ">            <username>tester</username>        </p:getuserbyname >    </soap: Body></soap:envelope>

Similarly, the client will use the HTTP POST method to send the above SOAP message to Http://localhost:8182/v1/soap/servlet/messagerouter Uri,soap The response returned after server processing is as follows:

Getuserbynameresponse SOAP Message

<?xml version= "1.0" encoding= "UTF-8" standalone= "no"? ><soap:envelope xmlns:soap= "/http/ schemas.xmlsoap.org/soap/envelope/">    <soap:Body>        <p:getuserbynameresponse xmlns:p="/http Www.exmaple.com ">            <name>tester</name>            <title>software engineer</title>            <company>IBM</company>            <email>[email protected]</email>            <description> testing!</description>        </p:getUserByNameResponse>    </soap:Body></soap:Envelope>

In fact, the process of creating a new user is similar, not listed here, because these two examples are sufficient for this article to compare rest and soap at selected points.

Rest versus soap Comparison

This section compares the rest implementation with the SOAP implementation in the above two sections.

Interface Abstraction

While RESTful Web services use standard HTTP methods (Get/put/post/delete) to abstract the service capabilities of all Web systems, the difference is that SOAP applications abstract Web services by defining their own personalized interface methods, which is more like the RPC we often talk about. For example, the Getuserlist and Getuserbyname methods in this example.

RESTful Web services use the advantages of standard HTTP methods, in large terms: standardized HTTP operation methods, combined with other standardized technologies, such as Uri,html,xml, will greatly improve the interoperability between systems and systems. Especially in Web applications, the abstraction that RESTful Web Services Express is more natural than the way the web itself works. At the same time, the Rrestful Web service implemented using the standard HTTP method also brings some advantages of the HTTP method itself:

Non-stateful (stateless)

The HTTP protocol is essentially a stateless protocol, where HTTP requests from clients can be isolated from each other, and there is no mutual state dependency. HTTP-based Roa, which implements stateless service request processing logic in a very natural way. For distributed applications, any given two service requests request 1 with request 2, because they do not have a state dependency between them, they do not need to collaborate with each other, the result is: request 1 and request 2 can be executed on any server, Such an application can easily support load balancing (load-balance) on the server side.

Security operations and power-reference equality characteristics (safety/idempotence)

HTTP request should essentially be a secure call, that is: call does not have any side effects, does not cause the server side state changes. For a server, the client makes N-times a GET, haed call to a URI, and its state is the same as not making a call, and no change will occur.

The put, delte invocation of HTTP has a power-reference equality feature, that is, the client makes N-times a put, delte call to a URI, and the effect is the same as the call to do it once. The Get and head methods of HTTP also have power-reference equality attributes.

HTTP these standard methods guarantee in principle that your distributed system has these features to help build a more robust distributed system.

Safety control

To illustrate the problem, based on the above online user management system, we have given the following scenarios:

Referring to the use case diagram we gave at the outset, for client Client2, we only want it to access the user and user list resources in a read-only manner, and Client1 has all the permissions to access all the resources.

How do you do this security control?

The common practice is that all HTTP requests made from client Client2 are proxied (proxy server). The proxy server formulates a security policy: all requests that go through the agent's access to the user and user list resources have read access only, that is, allow get/head operations, and Put/delte like write permissions are not allowed.

For rest, let's see how this security policy is deployed. As shown in the following:

Rest and Proxy server (proxies Servers)

The implementation of a generic proxy server determines the security legitimacy of an HTTP request based on a two-tuple (URI, HTTP Method). When a request similar to (Http://localhost:8182/v1/users/{username},delete) is found, it is rejected. For soap, if we want to use the existing proxy server for security control, it will be more embarrassing, such as:

Soap and proxy servers (proxy Servers)

All SOAP messages go through a proxy server and can only look at (Http://localhost:8182/v1/soap/servlet/messagerouter, HTTP POST) information, If the proxy server wants to know what the current HTTP request is doing, it must decode the soap's message body, which means that the proxy server for the third party needs to understand the current SOAP message semantics, which is not justified by the tight coupling between the SOAP application and the proxy server.

About caching

As we all know, for network-based distributed applications, network transmission is an important factor affecting application performance. How to use caching to save the overhead of network transport is an issue that every developer who constructs a distributed network application must consider.

The HTTP protocol conditional HTTP GET request (Conditional get) is designed to save the overhead of network transport between the client and the server, which also provides the possibility for the client to implement the cache mechanism, including any proxy between the client and the server. The HTTP protocol implements a conditional get request through the HTTP HEADER domain: If-modified-since/last-modified,if-none-match/etag.

Rest applications can fully exploit the HTTP protocol's ability to support caching. When the client first sends an HTTP GET request to the server for content, the content may be cached by the cache server. The next time the client requests the same resource, the cache can give a direct response without requiring the remote server to obtain it. And all of this is transparent to the client.

Rest and cache servers (cache server)

And for soap, what's the situation?

Soap using the HTTP protocol, because its design in principle does not emphasize the same as rest, and the way the Web works, so it is very difficult to make full use of the HTTP itself caching capabilities based on SOAP applications.

Soap and cache servers (cache server)

Two factors determine that the caching mechanism for SOAP-based applications is far more complex than rest:

First, all the SOAP messages that go through the cache server are always HTTP POST, and if the cache server does not decode the SOAP message body, it cannot know if the HTTP request is to obtain data from the server.

Second, the URI used by the SOAP message always points to the server of soap, as in this example, Http://localhost:8182/v1/soap/servlet/messagerouter, which does not express the actual resource URI. As a result, the cache server is unaware that the resource is being requested, not to mention cache processing.

About connectivity

In a pure SOAP application, a URI is inherently meaningless except to indicate a SOAP server. Unlike rest, soap method calls cannot be driven by URIs. In our case, for example, when we get all the user lists through Getuserlist SOAP messages, we still can't get a specific user information through the information we have. The only way to do this is through the instructions of the WSDL, obtained by calling Getuserbyname, Getuserlist and getuserbyname are isolated from each other. For rest, the situation is completely different: Get a list of users through the Http://localhost:8182/v1/users URI, and then pass the Link property provided in the user list, such as <link>http://localhost:8182/v1/users/tester</link> obtaining user information for the tester user. This works very much like when you click on a hyperlink on a page of a browser, and the browser automatically directs you to the page you want to visit, and does not rely on any third party information.


A typical SOAP-based Web service is operations-centric, with each operation accepting an XML document as input and providing an XML document as output. In essence, they are RPC-style. In a ROA application that follows the rest principle, the service is resource-centric and the operation of each resource is a standardized HTTP method.

This paper focuses on the above aspects, the comparison between soap and rest, we can see that the rest-based system has a better ability to expand its system than soap, which can be reflected in its unified interface abstraction, Proxy server support, cache server support and many other aspects. And, with the evolving trend of Web Site as Web services, based on the simplicity and extensibility of restful design and implementation, there is reason to believe that rest will become an important architectural practice area for Web services.

Ultimate Summary

SOAP (Simple Object Access Protocol) is a tightly defined information exchange protocol used to encapsulate remote calls and returns in a Web service into machine-readable formatted data. In fact, SOAP data uses an XML data format that defines a complex set of tags that describe the remote procedures, parameters, return values, error messages, and so forth of the call. And with the need to grow, and not to increase the protocol to support security, this makes soap unusually large, deviating from the simple intention. On the other hand, each server can launch its own API based on this protocol, even if the services they provide are similar, the defined APIs are different, which leads to the creation of WSDL. WSDL (Web service Description Language) also follows the XML format to describe which server provides what services,
How to find it, and what interface specifications the service uses, in short, service discovery. Now, the process of using the Web service becomes, obtains the WSDL description of the service, constructs a formatted SOAP request based on the WSDL to send to the server, then receives an answer in the same soap format, and finally decodes the data based on the previous WSDL. In most cases, the request and the reply are transmitted using the HTTP protocol, then the send request uses the HTTP POST method.

The REST (representational state transfort) Form should be expressed as the client through the application of resources to achieve the transformation of the status, in this perspective the system can be regarded as a virtual state machine. Throw away R. The obscure theory in Dr. T. Fielding's thesis does not say that rest should satisfy such a feature:

    1. client and server structure;
    2. The connection protocol has the status of Stateless;
    3. Can use the cache mechanism to improve performance;
    4. hierarchical system;
    5. On-demand code;

After all, rest is just an architectural style, not a protocol or a standard. But this new style (perhaps already has a long history?) The impact of the existing SOAP-based Web service is also revolutionary, because it is resource-oriented, and even services are abstracted as resources because it is tightly bound to HTTP because it has a stateless server.

Because SOAP does not assume a lower-level protocol for transmitting data, it must be designed to run on a variety of protocols. Even though the vast majority of soap runs on HTTP and uses the URI to identify the service, SOAP simply sends the request using the Post method, identifying the portal of the service with a unique URI.

Rest is simple and intuitive, using the HTTP protocol to the limit, and under the guidance of this idea, it even uses the header information of the HTTP request to indicate the resource's representation (if a resource has multiple forms, such as human-friendly pages or machine-readable data?). ), using an HTTP error mechanism to return an error accessing the resource. The immediate benefit is that the cost of the build is reduced, such as using URIs to locate each resource can take advantage of a common, proven technology without having to develop a set of resource access mechanisms on the server side. You can also specify access to resources by simply configuring the server, such as by prohibiting non-get access to make the resource read-only.

Server stateless brings additional benefits because each request contains all the information needed to respond, all state information is stored on the client, and the server's memory is freed from the huge state information. And now even a sudden crash of a server has a negligible impact on the customer, because another server can immediately replace its location without having to consider recovering state information. More caches are also possible, and requests to the same URI can cause a completely different response because the server is stateful.

The overall result is that the network's fault tolerance and ductility are enhanced, which is originally the original purpose of web design, the increasingly complex and customized web to destroy them, and now rest is back to basics, trying to bring Web service back to simple principles.

But is rest the almighty? Stateless brings a huge advantage, and it also brings problems that are difficult to solve, such as how to empower a specific user to use a service? How do I verify a user's identity? If you persist the server stateless, that is, do not log the user logon status, it is bound to require that each service request contains the full user identity and authentication information. In this case, how to avoid the risk of recognition? How to avoid user information leakage? In fact, building a rest-attached security mechanism is already under discussion, and the result is nothing more than another soap: complex requirements that devastate ease of use.

Rest supporters claim that rest requests and response data are simple to read, while SOAP requires a tedious package, and even so, soap is still unable to achieve interface consistency, and the different vendors have their own interfaces, while rest uses only HTTP-defined methods and is therefore generic. Is that really the case? Imagine a service that uses rest to achieve two sums, and if, as suggested, the service (here is the addition) as a resource, the parameter (here is two addend) as the parameter of the request, the result is returned in XML or JSON syntax, is it easier to use than soap? The generic interface still cannot be reached because the name of the resource, the name of the parameter, and the format of the result are still defined by the service provider.

To solve this problem, WASL (Web application Description Language) is proposed to describe the rest interface. Wadl is like the rest version of WSDL, where the shadow of soap is everywhere as rest is applied to complex fields.

Resource-oriented and transaction-oriented (it is very clear that the trial scope of rest, request map data can be considered primarily to request a special kind of resources) rest in resource-oriented applications, but in the application of transaction-oriented is not satisfactory. Resource-oriented application operation is simple, nothing but create, read, change, delete a few items, but the transaction-oriented application does not allow users to manipulate resources directly, the user only need to submit a transaction description requirements to the system, and then wait for the completion of the transaction, such as an online banking users do not directly modify the account and deposit, Instead, submit a transaction to tell the bank to transfer the money itself. If you consider such a service as a resource, by sending a POST request to the resource to complete the transaction, it is just a copy of the soap, either this, or by putting to create the transaction, all change the state of the system (the resource itself has not changed, here is to change the user's balance), Clearly violates the intuitive purpose of rest.

In fact, the rest API provided by some Web service providers is only the rest of the shell, and the transfer of requests and responses is completely simplified soap, and this new bottle of old wine has only deepened the standards of disagreement. In the final analysis, rest cannot simply solve some applications,
So we can only see the reincarnated of soap under the rest shell. No technology can solve all problems once and for all, and it is sufficient to gracefully solve the problem in the field under the predetermined constraints. The introduction of a new technology has always attracted countless follow-up and flattery, only when the dust settles down to get a fair evaluation.

A discussion on service-side rest and soap

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.