Building SOA composite business services, Part 3: Build consumable Web Services using the REST architectural style in WebSphere

This article is the third in a series about developing composite applications to enable business services. The article focuses on the Representational State Transfer (REST) architectural style. By using a facade component as a REST-style interface, existing SOAP-style Web services can support customizable URLs, multiple resource format representations, browser response caching, streaming of large attachments, and use of HTTP methods to manipulate the resource.

Indrajit Poddar (ipoddar@us.ibm.com), Advisory Software Engineer, IBM, Software Group

Indrajit Poddar is a member of the Strategy, Technology, Architecture and Incubation team in the IBM Software Group Strategy division, where he is developing several integration proofs of concept for building composite business services. He has a master's degree in Computer Science and Engineering from Penn State University, and he has a bachelor's degree in Computer Science and Engineering from the Indian Institute of Technology, Kharagpur, India. He received an IBM Outstanding Technical Achievement Award in 2005 for his contributions to the Memory Dump Diagnostic for Java tool.



Zhi Gan (ganzhi@cn.ibm.com), Software Engineer, IBM

Zhi Gan is a software engineer at the IBM China Development Lab. He joined IBM after receiving a Ph.D. in computer security from Shanghai JiaoTong University. He has extensive experience in SOA, AOP, and Eclipse. Now he focuses mainly on model-driven development with patterns.



Yue Lin Liu (yuelin_liu@msn.com), Software Engineer, IBM

Yue Lin Liu has eight years of experience in software architecture and development of J2EE, SOA, MDA, PKI, AOP, and grid computing applications. He focuses on patterns and architecture of enterprise applications.



12 February 2007

Also available in Chinese Russian

Introduction

The Representational State Transfer (REST) architectural style offers a low-barrier entry point for consuming Web services. The external interface of a typical REST-style application consists of a large number of Uniform Resource Identifier (URI) addressable resources and a few operations, such as Create, Read, Update, and Delete (CRUD). The advantage of this architectural style is its simplicity.

Developer and author Paul Prescod defines a REST Web service as "a Web service that delivers its functionality entirely as a set of URI-addressable resources using the syntax and semantics of the HTTP protocol" (see Resources). You can see an example of the REST style as ubiquitously as the World Wide Web itself. The HTTP protocol underlying the Web uses Uniform Resource Locators (URLs) to denote resources and a few well-known HTTP methods, such as GET, POST, PUT, HEAD, and DELETE to manipulate the resources. This simple architectural style allows scalability and interactivity by reusing the Web's loosely coupled and distributed infrastructure.

This article presents an example of a business service for a bank that publishes mortgage rates to an aggregator Web site like Bankrate (see Resources). Aggregator Web sites typically gather information from a number of different providers and aggregate them in a client-side mashup. This is also referred to as composition on the glass and can be considered a composite application. To enable easy construction of such mashups, service providers need to expose a simplified interface. The REST architectural style is a perfect fit for this requirement.

This article proposes the use of a facade component for providing a REST-style interface to existing SOAP-style Web services. The article describes the component's desirable functions and captures those functions in a Rational® Software Architect Reusable Asset Specification (RAS) pattern. This pattern is parameterized by an endpoint and an operation of an existing Web service. This pattern can be transformed into a deployable Java™ 2 Enterprise Edition (J2EE) servlet implementation that invokes the existing Web service. This generated servlet supports desirable REST-style function, such as browser caching, resource content format negotiation, and HTTP streaming of large attachments using the SOAP Attachment for Java (SAAJ) standard.

Explore Resources for more information about URI, CRUD, mashups, the facade pattern, SOAP-style Web services, the RAS pattern, SAAJ, and other resources.


Desirable functions of a REST-style facade component

The following functions are desirable in a REST-style Web service facade component:

Customizable URL to denote a REST-style resource
The REST architectural style favors the use of URLs to provide access to fine-grained resources. For example, in a mortgage application, a mortgage rate that a bank offers on any particular date can be a needed resource. Having a different URL to represent each fine-grained resource enables other applications, such as email, to easily reference these resources. This also enables client-side composition of resources using Web 2.0 technologies, such as Ajax. Therefore, a Web service facade component enables application developers to customize the URL representing a resource.
HTTP methods, such as GET, POST, DELETE, PUT, TRACE, and OPTIONS to manipulate the resource
A REST-style Web service allows access to a resource through a small set of well-known operations, such as separate operations to get representations of the resource, to get information about the resource, and to manipulate the resource. The HTTP protocol already defines a small set of operations (GET, POST, PUT, and so on). (See Resources for more information about HTTP methods.) The facade component supports the use of these HTTP methods. Note that Web Service Description Language (WSDL) 1.1 for SOAP Web services supports only the HTTP POST method. WSDL 2.0 complements this by including support for the HTTP GET binding, but WSDL 2.0 is not yet supported in WebSphere® Application Server as of V6.1. Also note that the HTTP DELETE, PUT, TRACE, and OPTIONS methods are not frequently used and are often blocked by firewalls.
Resource representation and content format negotiation
Each resource accessed by a URL can be represented in different forms, depending on the client accessing the resource. The client could be an HTML browser on a desktop machine or another SOAP Web service or an Ajax or JavaScript Object Notation (JSON) client (see Resources). The facade component queries the HTTP request's Accept header field to determine the desired response format for the client and then serve the resource in the desired format.
Browser and gateway proxy caching of resource representations
REST-style interfaces are most commonly used for accessing resources using the HTTP GET method. For HTTP GET requests, the REST-style Web service can set HTTP response header fields to provide hints to the Web browser cache as to whether, how long, and with which validation or invalidation policies the resource representation returned can be cached. Enabling response caching helps to improve the application's scalability. The facade component sets the HTTP header Cache-Control response directive to PUBLIC, PRIVATE, and so on, appropriately.
Use of SAAJ to invoke SOAP-style Web services
A SOAP-style Web service returns the response in XML, which is often the desired resource representation format for REST-style clients. Therefore, a facade component avoids unnecessary unmarshalling overheads by accessing the SOAP response message in XML directly. To facilitate this, the facade component uses SAAJ to invoke the existing Web service. SAAJ can also enable streaming over HTTP of large amounts of data in attachments in the Web service response.

A RAS pattern for a REST-style Web service facade

In simple terms, a RAS pattern is a reusable asset that describes a solution to a recurring problem in a given context (see Resources for a link to the IBM Pattern solution Web site). Patterns can be captured using tools such as IBM Rational Software Architect (RSA) to automate solution development. The following sections describe a RAS pattern that captures the desirable functions of a REST-style Web service facade.


Download and install the pattern

See Downloads for a REST pattern and a transformation plug-in packaged into a reusable asset. Install the asset into RSA using the following steps:

  1. Unzip the download package.
  2. In Rational Software Architect, import the RestFeature.ras asset file through the File>Import window. Choose the RAS Asset type in the Import window. Go through the wizard pages to import the asset.
  3. Click Help>About IBM Rational Software Development Platform.
  4. To verify that the plug-in installed successfully, find the RestPattern Plug-in and RestPatternTransform Plug-in in the Plug-ins Details window, as shown in Figure 1.
Figure 1. View plug-ins
Figure 1. View plug-ins

Create a pattern instance

Follow these steps to create a pattern instance:

  1. Open the Pattern Explorer view with Window>Show View>PatternExplorer. The pattern should be available under the WEB2.0 group, as shown in Figure 2.
    Figure 2. View new pattern in the Pattern Explorer view
    View new pattern in the Pattern Explorer view
  2. Open the Modeling perspective in RSA, and create a new modeling project.
  3. Create a blank UML model in the newly created project.
  4. Drag and drop the pattern into the newly created model.

You have now created an instance of the RESTWebServiceFacade pattern. The next step is to fill in the parameters.


Specify pattern parameters

Specify the following parameters in the RESTWebServiceFacade pattern instance:

Table 1. Parameters supported by REST pattern
Parameter namePurpose
ExistingWebServiceEndPointThe endpoint of an existing SOAP Web service for which this pattern will generate a J2EE servlet facade. You can find the value in the SOAP Web service's WSDL file.
NameSpaceThe namespace of the existing SOAP Web service. This parameter is used when constructing a SOAP request message. You can find the value in the SOAP Web service's WSDL file.
OperationA single operation in the existing Web service that accesses an interesting resource.
ParameterA list of all parameters needed to invoke the operation.
FacadeURLContextPathThe context path of the target Web project. It is the first part of the URL for accessing the REST-style service. Multiple J2EE Web components can share a context path.
FacadeURLServletPathSpecifies the customizable part of the URL for accessing the resource represented by this facade.
HTTPMethodA list of supported HTTP methods. Only GET, POST, and DELETE are currently supported.
ReplyFormatThe supported resource representation format (for example, XML or HTML). The facade checks the HTTP request's Accept header to see if any of the supported format is requested and, if so, serves the resource in the requested format.
CacheSpecifies whether the response is cacheable or not by setting the HTTP response header's Cache-Control to Public.

Figure 3 shows an instance of the pattern. This instance can be used as a facade for an existing Web service operation with the following parameters:

  • The endpoint is http://localhost:9081/RESTRouter/service/RatesFacade.
  • The operation name is queryRate.
  • The namespace is http://ejbs.
  • The parameters are prodId (with a value such as Mortgage) and prodType (with a value such as 30-year fixed).

An example URL for accessing the REST-style rate resource is http://localhost:9080/bank/rate?prodId=Mortgage&prodType=30-year%20fixed, where servletPath is specified in the parameter as /rate and contextPath is specified as /bank. The resource representation formats supported in the service response are XML and HTTP, and the responses are cacheable as publicly available.

Figure 3. A pattern instance of the RESTWebServiceFacade pattern
A pattern instance of the RESTWebServiceFacade pattern

Transform the pattern into a J2EE servlet

Follow these steps to transform the pattern into a J2EE servlet:

  1. Create a dynamic Web project.
  2. Right-click the pattern, and select Transform>Pattern to WebServiceFacadeServlet, as shown in Figure 4.
  3. Specify the newly created Web project you created in Step 1.
Figure 4. Invoking the transformation
Figure 4. Invoking the transformation

Figure 5 shows the generated wrapper servlet.

Figure 5. Generated wrapper servlet
Figure 5. Generated wrapper servlet

Update, deploy, and invoke the generated J2EE servlet code

Follow these steps to update the generated code for supporting additional resource representation formats and for extracting attachments from SOAP messages:

  1. View the generated servlet code:
    • The specified HTTP methods are supported in the generated facade servlet by extending the J2EE HttpServlet abstract class and by implementing the corresponding J2EE servlet method, such as doGet, doPost, and doDelete.
    • Listing 1 shows the generated code, which invokes the preexisting Web service using SAAJ.
      Listing 1. Code example for invoking an existing SOAP Web service using SAAJ
      MessageFactory messageFactory = MessageFactory.newInstance();
      SOAPMessage message = messageFactory.createMessage();
      
      //Create objects for the message parts
      SOAPPart soapPart = message.getSOAPPart();
      SOAPEnvelope envelope = soapPart.getEnvelope();
      SOAPBody body = envelope.getBody();
      envelope.getHeader().detachNode();
      
      //Populate the body
      //Create the main element and namespace
      SOAPElement bodyElement = body.addChildElement(envelope
                  .createName(operation, "req", ns));
      
      //Add content
      bodyElement.addChildElement("prodid").addTextNode(para0);
      bodyElement.addChildElement("prodtype").addTextNode(para1);
      
      //Save the message
      message.saveChanges();
      
      URL endpoint = new URL(endPoint);
      SOAPMessage respMsg = connection.call(message, endpoint)
    • Listing 2 shows the generated code for supporting browser caching.
      Listing 2. Code example for setting browser caching HTTP header
      response.setHeader("Cache-Control", "public");
    • Listing 3 shows the generated code for resolving the appropriate resource representation and for setting the MIME content type appropriately.
      Listing 3. Code example for resource representation and content format negotiation
      String[] pattern_accepts={"text/xml"};
         String req_accepts = request.getHeader("Accept");
         RESTResourceRepresentationContext repContext = 
      new RESTResourceRepresentationContext();
         String format_decision = repContext.getAcceptFormat(pattern_accepts,
                  req_accepts);
      
         response.setContentType(format_decision);
         repContext.registerDefaultStrategies();
      repContext.generateAppropriateResourceRepresentation(respMsg,printer);
  2. Update the generated code. The following type of code changes might be needed:
    • Supporting a new resource representation format. In order to create custom reply format, create new strategy by inheriting from the RESTResponseStrategy class and registering it with the RESTResourceRepresentationContext class's registerStrategy() operation.
    • Use of SAAJ to obtain large attachments for streaming over HTTP. You can use the SoapMessage#getAttachments() method to extract attachments from the SOAP envelope. You can send attachments extracted in such a manner over the HTTP response object to the client.
  3. Deploy the Web project into a J2EE 1.4 application server as shown in Figure 5.
  4. Invoke the facade with the URL constructed from the parameters: http://localhost:9080/<FacadeURLContextPath>/<FacadeURLServletPath>?<Parameter=value>[: Parameter=value]
  5. See the result of the operation in your REST service client as shown in the example in Figure 6.
Figure 6. Visit the REST wrapper with Web browser
Visit the REST wrapper with Web browser

Source code for pattern plug-ins

You can modify the source code for the pattern plug-ins (see Downloads) to capture the best practices of your development organization for creating REST-style Web service facades.


When not to use the REST architectural style

Although the REST architectural style is appealing in many scenarios, it might not be suitable in some cases. The following are a few examples:

A remote procedure call style of service invocation is preferred over an unstructured request or response format.
For example, consider a transactional Web service that transfers money between two accounts. Support for transactional integrity is not available by default with REST-style Web services, but it can be added to SOAP-style Web services.
Multiple protocols are involved in the service invocation.
For example, consider whether you want to support an asynchronous style interface rather than a synchronous style.
Integration into business process through Business Process Execution Language (BPEL) is desired.
Currently BPEL processes do not support a REST-style interface. Only Service Component Architecture (SCA) components can be choreographed in a BPEL process.

Conclusion

A REST-style Web service facade provides certain desirable functions, such as multiple resource format representations, support for browser caching of responses, and support for other HTTP methods such as PUT, TRACE, and DELETE. The RAS pattern asset provided in this article captures the best practices for developing a REST-style Web service facade.


Acknowledgments

The authors would like to thank Lawrence Mandel, Thomas Schaeck, Chris Brealey, Christopher Hepper, Stefan Hepper, Kelvin Lawrence, Noah Mendelsohn, Mark Phillips, Luciano Resende, Arthur Ryman, and Tony Storey for providing input on the desired functions of a REST-style facade. The authors would also like to thank Aimee Dean and Patrick Flanders for their editorial review.


Downloads

DescriptionNameSize
REST Web Service RAS patternrestsrc.zip318KB
RestFeature RAS filesRestFeature.ras525KB

Resources

Learn

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into SOA and web services on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=SOA and web services, WebSphere, Architecture
ArticleID=195380
ArticleTitle=Building SOA composite business services, Part 3: Build consumable Web Services using the REST architectural style in WebSphere
publish-date=02122007