Sunday, July 31, 2016

When Should Use REST VS SOAP web services?


SOAP relies on XML (Extensible Markup Language) in three ways; the Envelope – that defines what is in the message and how to process it, a set of encoding rules for data types, and finally the layout of the procedure calls and responses gathered. This envelope is sent via a transport (HTTP/HTTPS), and an RPC (Remote Procedure Call) is executed and the envelope is returned with information in a XML formatted document.

It is important to note that one of the advantages of SOAP is the use of the “generic” transport. While REST today uses HTTP/HTTPS, SOAP can use almost any transport to send the request, using everything from the mentioned to SMTP (Simple Mail Transfer Protocol) and even JMS (Java Messaging Service). However, one perceived disadvantage is the use of XML because of the verboseness of it and the time it takes to parse.

However, the good news for web developers is that both technologies are very viable in today’s market. Both REST and SOAP can solve a huge number of web problems and challenges, and in many cases each can be made to do the developers bidding, which means they can work across the domain.

But the untold story is that both technologies can be mixed and matched. REST is very easy to understand and is extremely approachable, but does lack standards and is considered an architectural approach. In comparison, SOAP is an industry standard with a well-defined protocol and a set of well-established rules to be implemented, and it has been used in systems both big and small.

So this means areas that REST works really well for are:
  • Limited bandwidth and resources; remember the return structure is really in any format (developer defined). Plus, any browser can be used because the REST approach uses the standard GETPUTPOST, and DELETE verbs. Again, remember that REST can also use the XMLHttpRequest object that most modern browsers support today, which adds an extra bonus of AJAX.
  • Totally stateless operations; if an operation needs to be continued, then REST is not the best approach and SOAP may fit it better. However, if you need stateless CRUD (Create, Read, Update, and Delete) operations, then REST is it. (Communication between clients and servers must be stateless: servers should not store any information about the context of clients between calls, with the exception of session information that is used to maintain authentication).
  • Caching situations; if the information can be cached because of the totally stateless operation of the REST approach, this is perfect.
That covers a lot of solutions in the above three. So why would I even consider SOAP? Again, SOAP is fairly mature and well-defined and does come with a complete specification. The REST approach is just that, an approach and is wide open for development, so if you have the following then SOAP is a great solution:

  • Asynchronous processing and invocation; if your application needs a guaranteed level of reliability and security then SOAP 1.2 offers additional standards to ensure this type of operation. Things like WSRM – WS-Reliable Messaging.
  • Formal contracts; if both sides (provider and consumer) have to agree on the exchange format then SOAP 1.2 gives the rigid specifications for this type of interaction.
  • Stateful operations; if the application needs contextual information and conversational state management then SOAP 1.2 has the additional specification in the WS* structure to support those things (Security, Transactions, Coordination, etc). Comparatively, the REST approach would make the developers build this custom plumbing.

As shown above, each technology approach has their uses. They both have underlying issues around security, transport layers, and the like, but they both can get the job done and in many cases, they each bring something to the web. So for this argument, the best rule, is the rule of flexibility, because no matter what the problem at least in today’s web development world, web developers have great solutions using either of these protocols.

Creating JAX-RS web service using Apache CXF Example


Ever since JAX-RS was introduced (JSR-311), it had a profound effect on the architecture and design of web services. It is simplified scheme of creating an exposable service had really made an impact to how developers create web services as well as how it’s being used on the micro-service architecture. With this, a lot of service frameworks was introduced to create a more standardize and conventional way of following this scheme with more functional aspects to it. The list includes JerseyRestEasy and for our topic of tutorial for this post: Apache CXF.

What is Apache CXF?
Apache CXF is a service framework that can be used by developers to create exposable and reusable web services. It supports almost every web service specification available and has a wide range of wrappers that can be used in binding, parsing and manipulating data. It’s extremely light weight and easy to plugin to any Java based applications.
For this scenario, we’re going to create a micro-service, deploy and consume it through the front-end app.

How do we build?
Let’s start with a scenario. Let’s try to expose a service (contract first) that will display an account detail given an account id. The service specs:

  • Service will accept account id as an input
  • Return the JSON format account id and name

Step by Step Guide
1. Create the Web App using Maven and download the Apache CXF dependencies
Download the Apache CXF distribution first, use the following Maven dependency on your project. Configure your project to enable all request to go through Apache CXF framework.
  1. Go to New > Maven Project
  2. Group Id: com.jcg.areyes.main
  3. Artifact Id: apache-cxf-sample
  4. Archetype Template: J2EE Simple WebApp

Pom.xml
                        

As it can be seen in the screenshot above, we imported the JAX-RS library from Apache CXF and http transport api that handles the transportation from process from start to end points.

2. Configure Apache CXF in the Web App.
The web app should be configured to use the Apache CXF Servlet for a specific URL path. This will allow the Apache CXF library to get the request and run all necessary process to create and call the service at run-time.

Web.xml

  
         

We configure our web.xml so that it will detect any URL to pass through the CXF service.

rest-servlet.xml

                    

This file is imported from web.xml. This holds the actual services and the jaxrs service declaration.

3. Create the Service Implementation on the App
Create the Account Object first. This is the object that we will return from our service.

Account.java
package server.obj;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Account")
public class Account {
    private long id;
    private String name;
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Create the Service Implementation class. This will house our actual implementation.

AccountService.java
package server.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import server.obj.Account;
@Path("/accountservice/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class AccountService {
            Map accounts = new HashMap();
            public void init() {
                        Account newAccount1 = new Account();
                        newAccount1.setId(1);
                        newAccount1.setName("Alvin Reyes");
                        Account newAccount2 = new Account();
                        newAccount2.setId(2);
                        newAccount2.setName("Rachelle Ann de Guzman Reyes");
                        accounts.put("1", newAccount1);
                        accounts.put("2", newAccount2);
            }
            public AccountService() {
                        init();
            }
            @POST
            @Path("/accounts/{id}/")
            public Account getAccount(@PathParam("id") String id) {
                        Account c = accounts.get(id);
                        return c;
            }
            @POST
            @Path("/accounts/getall")
            public List getAllAccounts(Account account) {
                        List accountList = new ArrayList();
                        for (int i = 0; i <= accounts.size(); i++) {
                                    accountList.add((Account) accounts.get(i));
                        }
                        return accountList;
            }
}

As it can be seen above, there’s a bunch of Annotations that we used. These annotations are crucial as it allows the JVM to categorize this source code to have a configuration injected to it and Apache CXF to notice that we are using its libraries. The following annotations are described below:
  • @Path – The endpoint url path.
  • @Get – This means that the method is called using the GET http method.
  • @Produce – the response output format.
  • @QueryParam – Query parameters passed via the URL.
4. Test out the service
Once everything is in place, we can now test the service. Test it via your browser or a chrome extension (Poser).



RESTFul Web Service Interview Questions



What is a REST and RESTful web service?
REST stands for REpresentational State Transfer (REST), it’s a relatively new concept of writing web services which enforces a stateless client server design where web services are treated as resource and can be accessed and identified by their URL unlike SOAP web services which were defined by WSDL.
Web services written by apply REST Architectural concept are called RESTful web services which focus on System resources and how state of Resource should be transferred over http protocol to a different clients written in different languages. In RESTful web services http methods like GET, PUT, POST and DELETE can be used to perform CRUD operations.

What is difference between top-down and bottom-up approach of developing web services?
In top-down approach first WSDL document is created and then Java classes are developed based on WSDL contract, so if WSDL contract changes you got to change your Java classes while in case of bottom up approach of web service development you first create Java code and then use annotations like @WebService to specify contract or interface and WSDL field will be automatically generated from your build.

What happens if RestFull resources are accessed by multiple clients? Do you need to make it thread-safe?
Since a new Resource instance is created for every incoming Request there is no need to make it thread-safe or add synchronization. Multiple clients can safely access RESTful resources concurrently.

Can I use GET request instead of PUT to create resources?
No, you are supposed to use PUT or POST. GET operations should only have view rights.

What is meant by JAX-WS and JAX-RS?
Java API for XML Web Services(JAX-WS)
Java API for RESTful Web Services (JAX-RS)

What are the different application integration styles?
There is a number of different integration styles like
1. Shared database
2. Batch file transfer
3. Invoking remote procedures (RPC)
4. Exchanging asynchronous messages over a message oriented middle-ware (MOM).

How would you decide what style of Web Service to use? SOAP WS or REST?
In general, a REST based Web service is preferred due to its simplicity, performance, scalability, and support for multiple data formats. SOAP is favored where service requires comprehensive support for security and transactional reliability.
The answer really depends on the functional and non-functional requirements. Asking the questions listed below will help you choose.

Does the service expose data or business logic? (REST is a better choice for exposing data, SOAP WS might be a better choice for logic).Do the consumers and the service providers require a formal contract? (SOAP has a formal contract via WSDL)
Do we need to support multiple data formats?
Do we need to make AJAX calls? (REST can use the XMLHttpRequest)
Is the call synchronous or asynchronous?
Is the call stateful or stateless? (REST is suited for stateless CRUD operations)
What level of security is required? (SOAP WS has better support for security)
What level of transaction support is required? (SOAP WS has better support for transaction management)
Do we have limited band width? (SOAP is more verbose)
What’s best for the developers who will build clients for the service? (REST is easier to implement, test, and maintain)

What tools do you use to test your Web Services?
SoapUI tool for SOAP WS and the Firefox “poster” plugin for RESTFul services.

What is a difference between RESTful web services and SOAP web services?
Though both RESTful web series and SOAP web service can operate cross platform they are architecturally different to each other, here is some of differences between REST and SOAP:

1) REST is more simple and easy to use than SOAP. REST language is based on use of nouns and verbs (better readability)

2) REST uses HTTP protocol for producing or consuming web services while SOAP uses XML.
The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP SMTP, etc.
The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.

3) REST is lightweight as compared to SOAP and preferred choice in mobile devices and PDA’s. REST does not need XML parsing, no message header (to and from), hence less bandwidth

4) REST supports different format like text, JSON and XML while SOAP only support XML.
The SOAP WS permits only XML data format. You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service.
The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations.
GET – represent()
POST – acceptRepresention()
PUT – storeRepresention()
DELETE – removeRepresention()

5) SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better.

6) Different error handling:
REST: requires HTTP error handling
SOAP: can have user defined error

7) REST only supports synchronous message because of its reliance of HTTP and HTTPS

8) SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc.
The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not.

9) The SOAP has comprehensive support for both ACID based  transaction management  for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources.
The REST supports transactions, but it  is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.

10) The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.


Introduction to Restful Web Services


REST - Representational State Transfer

1.1. What is REST?
REST is an architectural style which is based on web-standards and the HTTP protocol. REST was first described by Roy Fielding in 2000. In a REST based architecture everything is a resource. A resource is accessed via a common interface based on the HTTP standard methods. In a REST based architecture you typically have a REST server which provides access to the resources and a REST client which accesses and modifies the REST resources.
Every resource should support the HTTP common operations. Resources are identified by global IDs (which are typically URIs). REST allows that resources have different representations, e.g., text, XML, JSON etc. The REST client can ask for a specific representation via the HTTP protocol (content negotiation).

1.2. HTTP methods
The PUTGETPOST and DELETE methods are typical used in REST based architectures. The following table gives an explanation of these operations.
  • GET defines a reading access of the resource without side-effects. The resource is never changed via a GET request, e.g., the request has no side effects (idempotent).
  • PUT creates a new resource. It must also be idempotent.
  • DELETE removes the resources. The operations are idempotent. They can get repeated without leading to different results.
  • POST updates an existing resource or creates a new resource.
Features of RESTful web services:
Resource identification through URI:Resources are identified by their URIs (typically links on internet). So, a client can directly access a RESTful Web Services using the URIs of the resources (same as you put a website address in the browser’s address bar and get some representation as response).
Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations: PUT, GET, POST, and DELETE.

Client-Server: A clear separation concerns is the reason behind this constraint. Separating concerns between the Client and Server helps improve portability in the Client and Scalability of the server components.

Stateless: each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server.

Cache: to improve network efficiency responses must be capable of being labeled as cacheable or non-cacheable.

Named resources - the system is comprised of resources which are named using a URL.

Interconnected resource representations - the representations of the resources are interconnected using URLs, thereby enabling a client to progress from one state to another.

Layered components - intermediaries, such as proxy servers, cache servers, gateways, etc, can be inserted between clients and resources to support performance, security, etc.

Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others.  


1.3. RESTFul web services
A RESTFul web services are based on HTTP methods and the concept of REST. A RESTFul web service typically defines the base URI for the services, the supported MIME-types (XML, text, JSON, user-defined, ...) and the set of operations (POST, GET, PUT, DELETE) which are supported.

2. JAX-RS with Jersey
2.1. JAX-RS
Java defines REST support via the Java Specification Request (JSR) 311. This specification is called JAX-RS (The Java API for RESTful Web Services). JAX-RS uses annotations to define the REST relevance of Java classes.
2.2. Jersey
Jersey is the reference implementation for the JSR 311 specification.
The Jersey implementation provides a library to implement Restful webservices in a Java servlet container.
On the server side Jersey provides a servlet implementation which scans predefined classes to identify RESTful resources. In your web.xml configuration file your register this servlet for your web application.
The Jersey implementation also provides a client library to communicate with a RESTful web service.
The base URL of this servlet is:
http://your_domain:port/display-name/url-pattern/path_from_rest_class
This servlet analyzes the incoming HTTP request and selects the correct class and method to respond to this request. This selection is based on annotations in the class and methods.
A REST web application consists, therefore, out of data classes (resources) and services. These two types are typically maintained in different packages as the Jersey servlet will be instructed via the web.xml to scan certain packages for data classes.
JAX-RS supports the creation of XML and JSON via the Java Architecture for XML Binding (JAXB).
2.3. JAX-RS annotations
The most important annotations in JAX-RS are listed in the following table.
Table 1. JAX-RS annotations

Annotation
Description
@PATH(your_path)
Sets the path to base URL + /your_path. The base URL is based on your application name, the servlet and the URL pattern from the web.xml configuration file.
@POST
Indicates that the following method will answer to an HTTP POST request.
@GET
Indicates that the following method will answer to an HTTP GET request.
@PUT
Indicates that the following method will answer to an HTTP PUT request.
@DELETE
Indicates that the following method will answer to an HTTP DELETE request.
@Produces(MediaType.TEXT_PLAIN[, more-types])
@Produces defines which MIME type is delivered by a method annotated with @GET. In the example text ("text/plain") is produced. Other examples would be "application/xml" or "application/json".
@Consumes(type[, more-types])
@Consumes defines which MIME type is consumed by this method.
@PathParam
Used to inject values from the URL into a method parameter. This way you inject, for example, the ID of a resource into the method to get the correct object.

The complete path to a resource is based on the base URL and the @PATh annotation in your class.
http://your_domain:port/display-name/url-pattern/path_from_rest_class


Difference between SOAP vs. REST




SOAP Web service
RESTful Web service
SOAP (Simple Object Access Protocol) is a standard communication protocol on top of transport protocols such as HTTP, SMTP, Messaging, TCP, UDP, etc.
REST is an architectural style by which data can be transmitted over transport protocol such as HTTP(S).
Each unique URL is a some representation of a resource (i.e Object like Account, Customer, etc), and you can get the contents of the resources (i.e Objects) via HTTP verb “GET” and to modify via “DELETE”,”POST”, or “PUT”.
SOAP uses its own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, which implement some business logic through different interfaces.
REST is about exposing a public API over the internet to handle CRUD (Create, Read, Update, and Delete) operations on data. REST is focused on accessing named resources through a single consistent interface.
SOAP only permits XML data formats.

REST permits many different data formats like XML, JSON data, text, HTML, atom, RSS, etc. JSON is less verbose than XML and is a better fit for data and parses much faster.
SOAP based reads cannot be cached. The application that uses SOAP needs to provide caching.
REST based reads can be cached. Performs and scales better.
Supports both SSL security and WS-security, which adds some enterprise security features. Supports identity through intermediaries, not just point to point SSL.
— WS-Security maintains its encryption right up to the point where the request is being processed.
— WS-Security allows you to secure parts (e.g. only credit card details) of the message that needs to be secured. Given that encryption/decryption is not a cheap operation, this can be a performance boost for larger messages.
— It is also possible with WS-Security to secure different parts of the message using different keys or encryption algorithms. This allows separate parts of the message to be read by different people without exposing other, unneeded information.
— SSL security can only be used with HTTP. WS-Security can be used with other protocols like UDP, SMTP, etc.
Supports only point-to-point SSL security.
— The basic mechanism behind SSL is that the client encrypts all of the requests based on a key retrieved from a third party. When the request is received at the destination, it is decrypted and presented to the service. This means the request is only encrypted while it is traveling between the client and the server. Once it hits the server (or a proxy which has a valid certificate), it is decrypted from that moment on.
— The SSL encrypts the whole message, whether all of it is sensitive or not.
Has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources.
REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.
SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries.
REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.

   
Which one to favor? In general, a REST based web service is preferred due to its simplicity, performance, scalability, and support for multiple data formats. SOAP is favored where service requires comprehensive support for security and transnational reliability.
SOA done right is more about RESTFul + JSON, favoring lighter weight approaches to moving messages around than the heavyweight ESBs using WSDL+XML that gave SOA a bad name