You are on page 1of 35

SOAP vs.

REST comparison
SOAP Web service

RESTful Web service


REST is an architectural style by which
data can be transmitted over transport
protocol such as HTTP(S).

SOAP (Simple Object Access Protocol) is a


standard communication protocol on top
of transport protocols such as HTTP, SMTP,
Messaging, TCP, UDP, etc.

SOAP Layers

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.

REST Layers

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.
URL:http://localhost:8080/myapp/createEm
ptyCase

RESTFull WebServices
1

SOAP

SOAP based reads cannot be cached. The


application that uses SOAP needs to provide
cacheing.
Supports both SSL security and WSsecurity, 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.

RESTFull WebServices
2

REST content XML, JSON, RSS, etc

REST based reads can be cached.


Performs and scales better.
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.

SSL security can only be used with HTTP.


WS-Security can be used with other
protocols like UDP, SMTP, etc.

Has comprehensive support for


both ACIDbased 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.

Q3. How would you decide what style of Web Service to use? SOAP WS or REST?
A3. 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.
1) 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).
2) Do consumers and the service providers require a formal contract? (SOAP has a formal
contract via WSDL)
3) Do we need to support multiple data formats?
4) Do we need to make AJAX calls? (REST can use the XMLHttpRequest)
5) Is the call synchronous or asynchronous?
6) Is the call stateful or stateless? (REST is suited for statless CRUD operations)
RESTFull WebServices
3

7) What level of security is required? (SOAP WS has better support for security)
8) What level of transaction support is required? (SOAP WS has better support for
transaction management)
9) Do we have limited band width? (SOAP is more verbose)
10) Whats best for the developers who will build clients for the service? (REST is easier to
implement, test, and maintain)

@Produces to specify the type of output this method (or web service) will produce.
@Consumes to specify the MIME media types a REST resource can consume
@Path to specify the URL path on which this method will be invoked.
@PathParam to bind REST style parameters to method arguments. For example
http://localhost:8080/context/accounting-services/PeterAndCo
@QueryParam to access parameters in query string
(http://localhost:8080/context/accounting-services?accountName=PeterAndCo).
@FormParam to read parameters sent in a POST request. REST resources usaually
consume XML/JSON, but at times you want to read the paramewters in POST.

HTTP methods
The PUT, GET, POST 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.

RESTFull WebServices
4

WSDL Abstract:

WSDL stands for Web Services Description Language

WSDL is an XML based protocol for information exchange in decentralized and distributed environments.

WSDL is the standard format for describing a web service.

WSDL definition describes how to access a web service and what operations it will perform.

WSDL is a language for describing how to interface with XML-based services.

WSDL is an integral part of UDDI, an XML-based worldwide business registry.

WSDL is the language that UDDI uses.

WSDL was developed jointly by Microsoft and IBM.

WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'

Objects in WSDL 1.1 / WSDL 2.0


WSDL 1.1
Term

WSDL 2.0
Term

Description

Service

Service

Contains a set of system functions that have been exposed to the Web-based protocols.

Port

Endpoint

Defines the address or connection point to a Web service. It is typically represented by a


simple HTTP URL string.

Binding

Binding

Specifies the interface and defines the SOAP binding style (RPC/Document) and transport
(SOAP Protocol). The binding section also defines the operations.

PortType

Interface

Defines a Web service, the operations that can be performed, and the messages that are
used to perform the operation.

Operation

Operation

Defines the SOAP actions and the way the message is encoded, for example, "literal." An
operation is like a method or function call in a traditional programming language.

Message

n/a

Typically, a message corresponds to an operation. The message contains the information


needed to perform the operation. Each message is made up of one or more logical parts.
Each part is associated with a message-typing attribute. The message name attribute
provides a unique name among all messages. The part name attribute provides a unique
name among all the parts of the enclosing message. Parts are a description of the logical
content of a message. In RPC binding, a binding may reference the name of a part in order
to specify binding-specific information about the part. A part may represent a parameter in
the message; the bindings define the actual meaning of the part. Messages were removed
in WSDL 2.0, in which XML schema types for defining bodies of inputs, outputs and faults
are referred to simply and directly.

Types

Types

Describes the data. The XML Schema language (also known as XSD) is used (inline or
referenced) for this purpose.

RESTFull WebServices
5

WSDL Usage:
WSDL is often used in combination with SOAP and XML Schema to provide web services over the Internet. A client
program connecting to a web service can read the WSDL to determine what functions are available on the server.
Any special data types used are embedded in the WSDL file in the form of XML Schema. The client can then
use SOAP to actually call one of the functions listed in the WSDL.

History of WSDL
WSDL 1.1 was submitted as a W3C Note by Ariba, IBM and Microsoft for describing services for the W3C XML
Activity on XML Protocols in March 2001.
WSDL 1.1 has not been endorsed by the World Wide Web Consortium (W3C), however it has just (May 11th, 2005)
released a draft for version 2.0, that will be a recommendation (an official standard), and thus endorsed by the W3C.

Description:
The WSDL describes services as collections of network endpoints, or ports. The WSDL specifications provides an
XML format for documents for this purpose. The abstract definitions of ports and messages are separated from their
concrete use or instance, allowing the reuse of these definitions. A port is defined by associating a network address
with a reusable binding, and a collection of ports defines a service. Messages are abstract descriptions of the data
being exchanged, and port types are abstract collections of supported operations. The concrete protocol and data
format specifications for a particular port type constitutes a reusable binding, where the operations and messages
are then bound to a concrete network protocol and message format. In this way, WSDL describes the public
interface to the Web service.

WSDL Definition Element


Posted by Dinesh Rajput

The <definition> element must be the root element of all WSDL documents. It defines the name of the web service.
Here is the example piece of code from last session which uses definition element.

1.
2.

<definitions name="HelloWorldService"
targetNamespace="http://www.dineshonjava.com/wsdl/HelloWorldService.wsdl"

RESTFull WebServices
6

3.
4.
5.
6.
7.

xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.dineshonjava.com/wsdl/HelloWorldService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
............................................

8.
9.

<definitions>

From the above example we can conclude the followings points:

The definitions element is a container of all the other elements.

The definitions element specifies that this document is the HelloWorldService.

The definitions element specifies a targetNamespace attribute. The targetNamespace is a convention of


XML Schema that enables the WSDL document to refer to itself. In this example we have specified
a targetNamespace ofhttp://www.dineshonjava.com/wsdl/HelloWorldService.wsdl.

The definition element specifies a default namespace: xmlns=http://schemas.xmlsoap.org/wsdl/. All


elements without a namespace prefix, such as message or portType, are therefore assumed to be part of the
default WSDLnamespace.

It also specifies numerous namespaces that will be used throughout the remainder of the document.

WSDL Message Element


Posted by Dinesh Rajput

The <message> element describes the data being exchanged between the Web service providers and
consumers.

Each Web Service has two messages: input and output.

The input describes the parameters for the Web Service and the output describes the return data from the
Web Service.

Each message contains zero or more <part> parameters, one for each parameter of the Web Service's
function.

Each <part> parameter associates with a concrete type defined in the <types> container element.
Lets take a piece of code from the Example Session:
1.
2.
3.
4.
5.
6.

<message name="SayHelloRequest">
<part name="firstName" type="xsd:string"/>
</message>
<message name="SayHelloResponse">
<part name="greeting" type="xsd:string"/>
</message>

Here, two message elements are defined. The first represents a request message SayHelloRequest, and the second
represents a response message SayHelloResponse.
Each of these messages contains a single part element. For the request, the part specifies the function parameters; in
this case, we specify a single firstName parameter. For the response, the part specifies the function return values; in
this case, we specify a single greeting return value.

RESTFull WebServices
7

WSDL portType Element


Posted by Dinesh Rajput

The <portType> element combines multiple message elements to form a complete oneway or round-trip operation.
For example, a <portType> can combine one request and one response message into a single request/response
operation. This is most commonly used in SOAP services. A portType can define multiple operations.
Lets take a piece of code from the Example Session:

1.
2.
3.
4.
5.
6.

<portType name="HelloWorld_PortType">
<operation name="sayHelloWorld">
<input message="tns:SayHelloRequest"/>
<output message="tns:SayHelloResponse"/>
</operation>
</portType>

The portType element defines a single operation, called sayHelloWorld.

The operation itself consists of a single input message SayHelloRequest

The operation itself consists of a single output message SayHelloResponse

Operation Types
The request-response type is the most common operation type, but WSDL defines four types:

Type

Definition

One-way

The operation can receive a message but will not return a


response

Request-response

The operation can receive a request and will return a response

Solicit-response

The operation can send a request and will wait for a response

Notification

The operation can send a message but will not wait for a
response

One-way :
The service receives a message. The operation therefore has a single input element. The grammar for a one-way
operation is:

1.
2.
3.
4.
5.
6.

<wsdl:definitions .... > <wsdl:portType .... > *


<wsdl:operation name="nmtoken">
<wsdl:input name="nmtoken"? message="qname"/>
</wsdl:operation>
</wsdl:portType >
</wsdl:definitions>

Request-response:
The service receives a message and sends a response. The operation therefore has one input element, followed by
one output element. To encapsulate errors, an optional fault element can also be specified. The grammar for a

RESTFull WebServices
8

request-response operation is:

1.
2.
3.
4.
5.
6.
7.
8.
9.

<wsdl:definitions .... >


<wsdl:portType .... > *
<wsdl:operation name="nmtoken" parameterOrder="nmtokens">
<wsdl:input name="nmtoken"? message="qname"/>
<wsdl:output name="nmtoken"? message="qname"/>
<wsdl:fault name="nmtoken" message="qname"/>*
</wsdl:operation>
</wsdl:portType >
</wsdl:definitions>

Solicit-response:
The service sends a message and receives a response. The operation therefore has one output element, followed by
one input element. To encapsulate errors, an optional fault element can also be specified. The grammar for a solicitresponse operation is:

1.
2.
3.
4.
5.
6.
7.
8.
9.

<wsdl:definitions .... >


<wsdl:portType .... > *
<wsdl:operation name="nmtoken" parameterOrder="nmtokens">
<wsdl:output name="nmtoken"? message="qname"/>
<wsdl:input name="nmtoken"? message="qname"/>
<wsdl:fault name="nmtoken" message="qname"/>*
</wsdl:operation>
</wsdl:portType >
</wsdl:definitions>

Notification :
The service sends a message. The operation therefore has a single output element. Following is the grammar for a
notification operation:

1.
2.
3.
4.
5.
6.
7.

<wsdl:definitions .... >


<wsdl:portType .... > *
<wsdl:operation name="nmtoken">
<wsdl:output name="nmtoken"? message="qname"/>
</wsdl:operation>
</wsdl:portType >
</wsdl:definitions>

WSDL Binding Element


Posted by Dinesh Rajput

The <binding> element provides specific details on how a portType operation will actually be transmitted
over the wire.

The bindings can be made available via multiple transports, including HTTP GET, HTTP POST, or SOAP.

The bindings provide concrete information on what protocol is being used to transfer portType operations.
The bindings provide information where the service is located.

RESTFull WebServices
9

For SOAP protocol, the binding is <soap:binding>, and the transport is SOAP messages on top
of HTTP protocol.
You can specify multiple bindings for a single portType.
The binding element has two attributes - the name attribute and the type attribute.
<binding name="HelloWorld_Binding" type="tns:HelloWorld_PortType">
The name attribute defines the name of the binding, and the type attribute points to the port for the binding, in this
case the "tns:HelloWorld_PortType" port.

SOAP Binding
WSDL 1.1 includes built-in extensions for SOAP 1.1. This enables you to specify SOAP specific details,
including SOAPheaders, SOAP encoding styles, and the SOAPAction HTTP header. The SOAP extension elements
include:
soap:binding
This element indicates that the binding will be made available via SOAP. The style attribute indicates the overall style
of theSOAP message format. A style value of rpc specifies an RPC format.
The transport attribute indicates the transport of the SOAP messages. The
value http://schemas.xmlsoap.org/soap/httpindicates the SOAP HTTP transport,
whereas http://schemas.xmlsoap.org/soap/smtp indicates the SOAP SMTP transport.
soap:operation
This element indicates the binding of a specific operation to a specific SOAP implementation.
The soapAction attribute specifies that the SOAPAction HTTP header be used for identifying the service.
soap:body
This element enables you to specify the details of the input and output messages. In the case of HelloWorld, the
body element specifies the SOAP encoding style and the namespace URN associated with the specified service.
Here is the piece of code from Example section:

<binding name="HelloWorld_Binding" type="tns:HelloWorld_PortType">


<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="sayHelloWorld">
<soap:operation soapAction="sayHelloWorld"/>
<input>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloworldservice"
use="encoded"/>
</input>
<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:dineshonjava:helloworldservice"
use="encoded"/>
</output>
</operation>
</binding>

RESTFull WebServices
10

WSDL Service Element


Posted by Dinesh Rajput

The <service> element defines the ports supported by the Web service. For each of the supported protocols,
there is one port element. The service element is a collection of ports.

Web service clients can learn from the service element where to access the service, through which port to
access the Web service, and how the communication messages are defined.

The service element includes a documentation element to provide human-readable documentation.


Here is a piece of code from Example Session:
1.
2.
3.
4.
5.
6.
7.

<service name="HelloWorld_Service">
<documentation>WSDL File for HelloWorldService</documentation>
<port binding="tns:HelloWorld_Binding" name="HelloWorld_Port">
<soap:address
location="http://www.dineshonjava.com/SayHelloWorld/">
</port>
</service>

The binding attributes of por element associate the address of the service with a binding element defined in the Web
service. In this example this is HelloWorld_Binding

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.

<binding name="HelloWorld_Binding" type="tns:HelloWorld_PortType">


<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="sayHelloWorld">
<soap:operation soapAction="sayHelloWorld"/>
<input>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloworldservice"
use="encoded"/>
</input>
<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:dineshonjava:helloworldservice"
use="encoded"/>
</output>
</operation>
</binding>

WSDL Ports Element


Posted by Dinesh Rajput

A <port> element defines an individual endpoint by specifying a single address for a binding.

The port element has two attributes - the name attribute and the binding attribute.

RESTFull WebServices
11

The name attribute provides a unique name among all ports defined within in the
enclosing WSDL document.

The binding attribute refers to the binding using the linking rules defined by WSDL.

A port MUST NOT specify more than one address.

A port MUST NOT specify any binding information other than address information.
Here is the piece of code from Example session:
1.
2.
3.
4.
5.
6.
7.

<service name="HelloWorld_Service">
<documentation>WSDL File for HelloWorldService</documentation>
<port binding="tns:HelloWorld_Binding" name="HelloWorld_Port">
<soap:address
location="http://www.dineshonjava.com/SayHelloWorld/">
</port>
</service>

Question 3 : What is HTTP Basic Authentication and how it works?

Question 4 : Can you tell me which API can be used to develop RESTFul web service in Java?
Answer : There are many framework and libraries out there which helps to develop RESTful web services in
Java including JAX-RS which is standard way to develop REST web services. Jersey is one of the popular
implementation of JAX-RS which also offers more than specification recommends. Then you also have
RESTEasy, RESTlet and Apache CFX. If you like Scala then you can also use Play framework to develop
RESTful web services.

Question 5 : How do you configure RESTFul web service?


Question 6 : How you apply security in RESTFul web services?
Question 7 : Have you used securing RESTful APIs with HTTP Basic Authentication
Question 8 : How you maintain session in RESTful services?

Question 9 : Have you used Jersey API to develop RESTful services in Java?
Answer : Jersey is one of the most popular framework and API to develop REST based web services in Java.
Since many organization uses Jersey they check if candidate has used it before or not. It's simple to answer, say
Yes if you have really used and No, if you have not. In case of No, you should also mention which framework
you have used for developing RESTful web services e.g. Apache CFX, Play or Restlet.

Question 10 : How you test RESTful web services?


Question 11 : What is WADL in RESTFul?

RESTFull WebServices
12

Question 12 : What do you understand by payload in RESTFul?


Answer : Payload means data which passed inside request body also payload is not request parameters. So
only you can do payload in POST and not in GET and DELTE method

Question 13 : Can you do payload in GET method?


Answer : No, payload can only be passed using POST method.

Question 14 : Can you do payload in HTTP DELETE?


Answer : This is again similar to previous REST interview question, answer is No. You can only pass payload
using HTTP POST method.

Question 15 : How much maximum pay load you could do in POST method?
Answer : If you remember difference between GET and POST request then you know that unlike GET which
passes data on URL and thus limited by maximum URL length, POST has no such limit. So, theoretically you
can pass unlimited data as payload to POST method but you need to take practical things into account e.g.
sending POST with large payload will consume more bandwidth, take more time and present performance
challenge to your server.

Question 16 : What is difference between SOAP and RESTFul web services?


Answer : There are many difference between these two style of web services e.g. SOAP take more bandwidth
because of heavy weight XML based protocol but REST takes less bandwidth because of popular use of JSON
as message protocol and leveraging HTTP method to define action. This also means that REST is faster than
SOAP based web services. You can derive many differences between SOAP and RESTful with the fact that its
HTTP based e.g. REST URLs can be cached or bookmarked. Here are few more differences between them :

Question 17 : If you have to develop web services which one you will choose SOAP OR RESTful and
why?

RESTFull WebServices
13

Answer : You can answer this question based upon your experience but the key here is if you know difference
between them than you can answer this question in more detail. For example, its easy to develop RESTful web
services than SOAP based web services but later comes with some in-built security features.

Question 18 : What framework you had used to develop RESTFul services?


Answer : This is really experience based question. If you have used Jersey to develop RESTFul web services
then answer as Jersey but expect some follow-up question on Jersey. Similarly if you have used Apache CFX or
Restlet then answer them accordingly.

That's all in this list of some good RESTful web service interview questions for Java developers. Though
this list is meant for Java developer, you can use this questions to check any candidate's knowledge on REST
style web services independent of programming language because REST doesn't say that you need to
implement web service in Java only. Since it take advantage of ubiquitous HTTP protocol you can build backed
with any web technology stack e.g. Java, .NET or any other.

1.

2. What is a Web Service?


Web Services work on client-server model where client applications can access web
services over the network. Web services provide endpoint URLs and expose methods that
can be accessed over network through client programs written in java, shell script or any
other different technologies.
Web services are stateless and doesnt maintain user session like web applications.

3. What are the advantages of Web Services?


Some of the advantages of web services are:
o

Interoperability: Web services are accessible over network and runs on HTTP/SOAP
protocol and uses XML/JSON to transport data, hence it can be developed in any
programming language. Web service can be written in java programming and client can be
PHP and vice versa.

Reusability: One web service can be used by many client applications at the same time.

Loose Coupling: Web services client code is totally independent with server code, so we
have achieved loose coupling in our application.

RESTFull WebServices
14

Easy to deploy and integrate, just like web applications.

Multiple service versions can be running at same time.

What are different types of Web Services?


There are two types of web services:
o

SOAP Web Services: Runs on SOAP protocol and uses XML technology for sending data.

Restful Web Services: Its an architectural style and runs on HTTP/HTTPS protocol almost
all the time. REST is a stateless client-server architecture where web services are resources
and can be identified by their URIs. Client applications can use HTTP GET/POST methods to
invoke Restful web services.

2.

What is SOAP?
SOAP stands for Simple Object Access Protocol. SOAP is an XML based industry standard
protocol for designing and developing web services. Since its XML based, its platform and
language independent. So our server can be based on JAVA and client can be on .NET, PHP
etc. and vice versa.

3.

What are advantages of SOAP Web Services?


SOAP web services have all the advantages that web services has, some of the additional
advantages are:
o

WSDL document provides contract and technical details of the web services for client
applications without exposing the underlying implementation technologies.

SOAP uses XML data for payload as well as contract, so it can be easily read by any
technology.

SOAP protocol is universally accepted, so its an industry standard approach with many
easily available open source implementations.

What are disadvantages of SOAP Web Services?


Some of the disadvantages of SOAP protocol are:

RESTFull WebServices
15

Only XML can be used, JSON and other lightweight formats are not supported.

SOAP is based on the contract, so there is a tight coupling between client and server
applications.

SOAP is slow because payload is large for a simple string message, since it uses XML
format.

Anytime there is change in the server side contract, client stub classes need to be generated
again.

Cant be tested easily in browser

What is WSDL?
WSDL stands for Web Service Description Language. WSDL is an XML based document
that provides technical details about the web service. Some of the useful information in
WSDL document are: method name, port types, service end point, binding, method
parameters etc.

What are different components of WSDL?


Some of the different tags in WSDL xml are:
o

xsd:import namespace and schemaLocation: provides WSDL URL and unique namespace
for web service.

message: for method arguments

part: for method argument name and type

portType: service name, there can be multiple services in a wsdl document.

operation: contains method name

soap:address for endpoint URL.

What is UDDI?

RESTFull WebServices
16

UDDI is acronym for Universal Description, Discovery and Integration. UDDI is a directory of
web services where client applications can lookup for web services. Web Services can
register to the UDDI server and make them available to client applications.

What is difference between Top Down and Bottom Up


approach in SOAP Web Services?
In Top Down approach first WSDL document is created to establish the contract between
web service and client and then code is written, its also termed as contract first approach.
This is hard to implement because classes need to be written to confirm the contract
established in WSDL. Benefit of this approach is that both client and server code can be
written in parallel.
In Bottom Up approach, first web service code is written and then WSDL is generated. Its
also termed as contract last approach. This approach is easy to implement because WSDL
is generated based on code. In this approach client code have to wait for WSDL from server
side to start their work.

What is REST Web Services?


REST is the acronym for REpresentational State Transfer. REST is an architectural style for
developing applications that can be accessed over the network. REST architectural style
was brought in light by Roy Fielding in his doctoral thesis in 2000.
REST is a stateless client-server architecture where web services are resources and can be
identified by their URIs. Client applications can use HTTP GET/POST methods to invoke
Restful web services. REST doesnt specify any specific protocol to use, but in almost all
cases its used over HTTP/HTTPS. When compared to SOAP web services, these are
lightweight and doesnt follow any standard. We can use XML, JSON, text or any other type
of data for request and response.

What are advantages of REST web services?


Some of the advantages of REST web services are:
o

Learning curve is easy since it works on HTTP protocol

RESTFull WebServices
17

Supports multiple technologies for data transfer such as text, xml, json, image etc.

No contract defined between server and client, so loosely coupled implementation.

REST is a lightweight protocol

REST methods can be tested easily over browser.

What are disadvantages of REST web services?


Some of the disadvantages of REST are:
o

Since there is no contract defined between service and client, it has to be communicated
through other means such as documentation or emails.

Since it works on HTTP, there cant be asynchronous calls.

Sessions cant be maintained.

What is a Resource in Restful web services?


Resource is the fundamental concept of Restful architecture. A resource is an object with a
type, relationship with other resources and methods that operate on it. Resources are
identified with their URI, HTTP methods they support and request/response data type and
format of data.

What are different HTTP Methods supported in Restful


Web Services?
Restful web services supported HTTP methods are GET, POST, PUT, DELETE and HEAD.

Compare SOAP and REST web services?


SOAP

SOAP is a standard protocol for creating web services.

RESTFull WebServices
18

REST

REST is an architectural style to create web services.

SOAP is acronym for Simple Object Access Protocol.

REST is acronym for REpresentational State Transfer.

SOAP uses WSDL to expose supported methods and

REST exposes methods through URIs, there are no technical

technical details.

details.

SOAP web services and client programs are bind with

REST doesnt have any contract defined between server and

WSDL contract

client

SOAP web services and client are tightly coupled with

REST web services are loosely coupled.

contract.

SOAP learning curve is hard, requires us to learn about

REST learning curve is simple, POJO classes can be

WSDL generation, client stubs creation etc.

generated easily and works on simple HTTP methods.

SOAP supports XML data format only

REST supports any data type such as XML, JSON, image


etc.

SOAP web services are hard to maintain, any change in

REST web services are easy to maintain when compared to

WSDL contract requires us to create client stubs again

SOAP, a new method can be added without any change at

and then make changes to client code.

client side for existing resources.

RESTFull WebServices
19

SOAP web services can be tested through programs or

REST can be easily tested through CURL command,

software such as Soap UI.

Browsers and extensions such as Chrome Postman.

What are different ways to test web services?


SOAP web services can be tested programmatically by generating client stubs from WSDL
or through software such as Soap UI.
REST web services can be tested easily with program, curl commands and through browser
extensions. Resources supporting GET method can be tested with browser itself, without
any program.

Can we maintain user session in web services?


Web services are stateless so we cant maintain user sessions in web services.

What is difference between SOA and Web Services?


Service Oriented Architecture (SOA) is an architectural pattern where applications are
designed in terms of services that can be accessed through communication protocol over
network. SOA is a design pattern and doesnt go into implementation.
Web Services can be thought of as Services in SOAP architecture and providing means to
implement SOA pattern.

What is the use of Accept and Content-Type Headers in


HTTP Request?
These are important headers in Restful web services. Accept headers tells web service what
kind of response client is accepting, so if a web service is capable of sending response in
XML and JSON format and client sends Accept header as application/xml then XML
response will be sent. For Accept header application/json, server will send the JSON
response.

RESTFull WebServices
20

Content-Type header is used to tell server what is the format of data being sent in the
request. If Content-Type header is application/xml then server will try to parse it as XML
data. This header is useful in HTTP Post and Put requests.

How would you choose between SOAP and REST web


services?
Web Services work on client-server model and when it comes to choose between SOAP and
REST, it all depends on project requirements. Lets look at some of the conditions affecting
our choice:
o

Do you know your web service clients beforehand? If Yes, then you can define a contract
before implementation and SOAP seems better choice. But if you dont then REST seems
better choice because you can provide sample request/response and test cases easily for
client applications to use later on.

How much time you have? For quick implementation REST is the best choice. You can
create web service easily, test it through browser/curl and get ready for your clients.

What kind of data format are supported? If only XML then you can go with SOAP but if you
think about supporting JSON also in future then go with REST.

What is JAX-WS API?


JAX-WS stands for Java API for XML Web Services. JAX-WS is XML based Java API to
build web services server and client application. Its part of standard Java API, so we dont
need to include anything else which working with it. Refer to JAX-WS Tutorial for a complete
example.

Name some frameworks in Java to implement SOAP


web services?
We can create SOAP web services using JAX-WS API, however some of the other
frameworks that can be used are Apache Axis and Apache CXF. Note that they are not
implementations of JAX-WS API, they are totally different framework that work on Servlet
model to expose your business logic classes as SOAP web services. Read more at Java
SOAP Web Service Eclipse example.

RESTFull WebServices
21

Name important annotations used in JAX-WS API?


Some of the important annotations used in JAX-WS API are:

@WebService

@SOAPBinding

@WebMethod

What is use of javax.xml.ws.Endpoint class?


Endpoint class provides useful methods to create endpoint and publish existing
implementation as web service. This comes handy in testing web services before making
further changes to deploy it on actual server.

What is the difference between RPC Style and


Document Style SOAP web Services?
RPC style generate WSDL document based on the method name and its parameters. No
type definitions are present in WSDL document.
Document style contains type and can be validated against predefined schema. Lets look at
these with a simple program. Below is a simple test program where I am using Endpoint to
publish my simple SOAP web service.
TestService.java

package com.journaldev.jaxws.service;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.Endpoint;
RESTFull WebServices
22

@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public class TestService {

@WebMethod
public String sayHello(String msg){
return "Hello "+msg;
}

public static void main(String[] args){


Endpoint.publish("http://localhost:8888/testWS", new
TestService());
}
}

When I run above program and then access the WSDL, it gives me below XML.
rpc.xml

<?xml

version='1.0' encoding='UTF-8'?>

<!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version


is JAX-WS RI 2.2.10 svnrevision#919b322c92f13ad085a933e8dd6dd35d4947364b. --><!-Generated by JAX-WS RI (http://jax-ws.java.net). RI's version is
JAX-WS RI 2.2.10 svnrevision#919b322c92f13ad085a933e8dd6dd35d4947364b. -->
RESTFull WebServices
23

<definitions xmlns:wsu="http://docs.oasisopen.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
xmlns:wsp="http://www.w3.org/ns/ws-policy"
xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy"
xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://service.jaxws.journaldev.com/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://service.jaxws.journaldev.com/"
name="TestServiceService">
<types/>
<message name="sayHello">
<part name="arg0" type="xsd:string"/>
</message>
<message name="sayHelloResponse">
<part name="return" type="xsd:string"/>
</message>
<portType name="TestService">
<operation name="sayHello">
<input
wsam:Action="http://service.jaxws.journaldev.com/TestService/sayHel
loRequest" message="tns:sayHello"/>
<output
wsam:Action="http://service.jaxws.journaldev.com/TestService/sayHel
loResponse" message="tns:sayHelloResponse"/>
</operation>
RESTFull WebServices
24

</portType>
<binding name="TestServicePortBinding" type="tns:TestService">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"
style="rpc"/>
<operation name="sayHello">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"
namespace="http://service.jaxws.journaldev.com/"/>
</input>
<output>
<soap:body use="literal"
namespace="http://service.jaxws.journaldev.com/"/>
</output>
</operation>
</binding>
<service name="TestServiceService">
<port name="TestServicePort" binding="tns:TestServicePortBinding">
<soap:address location="http://localhost:8888/testWS"/>
</port>
</service>
</definitions>

RESTFull WebServices
25

Notice that types element is empty and we cant validate it against any schema. Now just
change theSOAPBinding.Style.RPC to SOAPBinding.Style.DOCUMENT and you will get below
WSDL.
document.xml

<?xml

version='1.0' encoding='UTF-8'?>

<!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version


is JAX-WS RI 2.2.10 svnrevision#919b322c92f13ad085a933e8dd6dd35d4947364b. --><!-Generated by JAX-WS RI (http://jax-ws.java.net). RI's version is
JAX-WS RI 2.2.10 svnrevision#919b322c92f13ad085a933e8dd6dd35d4947364b. -->
<definitions xmlns:wsu="http://docs.oasisopen.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
xmlns:wsp="http://www.w3.org/ns/ws-policy"
xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy"
xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://service.jaxws.journaldev.com/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://service.jaxws.journaldev.com/"
name="TestServiceService">
<types>
<xsd:schema>
<xsd:import namespace="http://service.jaxws.journaldev.com/"
schemaLocation="http://localhost:8888/testWS?xsd=1"/>
</xsd:schema>
</types>

RESTFull WebServices
26

<message name="sayHello">
<part name="parameters" element="tns:sayHello"/>
</message>
<message name="sayHelloResponse">
<part name="parameters" element="tns:sayHelloResponse"/>
</message>
<portType name="TestService">
<operation name="sayHello">
<input
wsam:Action="http://service.jaxws.journaldev.com/TestService/sayHel
loRequest" message="tns:sayHello"/>
<output
wsam:Action="http://service.jaxws.journaldev.com/TestService/sayHel
loResponse" message="tns:sayHelloResponse"/>
</operation>
</portType>
<binding name="TestServicePortBinding" type="tns:TestService">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"
style="document"/>
<operation name="sayHello">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
RESTFull WebServices
27

<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="TestServiceService">
<port name="TestServicePort" binding="tns:TestServicePortBinding">
<soap:address location="http://localhost:8888/testWS"/>
</port>
</service>
</definitions>
Open schemaLocation URL in browser and you will get below XML.
schemaLocation.xml

<?xml

version='1.0' encoding='UTF-8'?>

<!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version


is JAX-WS RI 2.2.10 svnrevision#919b322c92f13ad085a933e8dd6dd35d4947364b. -->
<xs:schema xmlns:tns="http://service.jaxws.journaldev.com/"
xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0"
targetNamespace="http://service.jaxws.journaldev.com/">

<xs:element name="sayHello" type="tns:sayHello"/>

RESTFull WebServices
28

<xs:element name="sayHelloResponse" type="tns:sayHelloResponse"/>

<xs:complexType name="sayHello">
<xs:sequence>
<xs:element name="arg0" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="sayHelloResponse">
<xs:sequence>
<xs:element name="return" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
So here WSDL document can be validated against the schema definintion.

How to get WSDL file of a SOAP web service?


WSDL document can be accessed by appending ?wsdl to the SOAP endoint URL. In above
example, we can access it at http://localhost:8888/testWS?wsdl location.

What is sun-jaxws.xml file?


This file is used to provide endpoints details when JAX-WS web services are deployed in
servlet container such as Tomcat. This file is present in WEB-INF directory and contains
endpoint name, implementation class and URL pattern. For example;

RESTFull WebServices
29

sun-jaxws.xml

<?xml

version="1.0" encoding="UTF-8"?>

<endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
version="2.0">
<endpoint
name="PersonServiceImpl"

implementation="com.journaldev.jaxws.service.PersonServiceImpl"
url-pattern="/personWS"/>
</endpoints>

What is JAX-RS API?


Java API for RESTful Web Services (JAX-RS) is the Java API for creating REST web
services. JAX-RS uses annotations to simplify the development and deployment of web
services. JAX-RS is part of JDK, so you dont need to include anything to use its
annotations.

Name some implementations of JAX-RS API?


There are two major implementations of JAX-RS API.
o

Jersey: Jersey is the reference implementation provided by Sun. For using Jersey as our
JAX-RS implementation, all we need to configure its servlet in web.xml and add required
dependencies. Note that JAX-RS API is part of JDK not Jersey, so we have to add its
dependency jars in our application.

2.

RESTEasy: RESTEasy is the JBoss project that provides JAX-RS implementation.

What is wsimport utility?

RESTFull WebServices
30

We can use wsimport utility to generate the client stubs. This utility comes with standard
installation of JDK. Below image shows an example execution of this utility for one of JAXWS project.

3.

Name important annotations used in JAX-RS API?


Some of the important JAX-RS annotations are:
o

@Path: used to specify the relative path of class and methods. We can get the URI of a
webservice by scanning the Path annotation value.

@GET, @PUT, @POST, @DELETE and @HEAD: used to specify the HTTP request type for a
method.

@Produces, @Consumes: used to specify the request and response types.

@PathParam: used to bind the method parameter to path value by parsing it.

What is the use of @XmlRootElement annotation?


XmlRootElement annotation is used by JAXB to transform java object to XML and vice
versa. So we have to annotate model classes with this annotation.

How to set different status code in HTTP response?

RESTFull WebServices
31

For setting HTTP status code other than 200, we have to


use javax.ws.rs.core.Response class for response. Below are some of the sample return
statements showing its usage.
return Response.status(422).entity(exception).build();
return Response.ok(response).build(); //200

SOAP Tutorial - What is SOAP?


Posted by Dinesh Rajput

In this section we discuss all about SOAP Tutorial.


SOAP, originally defined as Simple Object Access Protocol, is a protocol specification for exchanging structured
information in the implementation of Web Services in computer networks. It relies on XML Information Set for its
message format, and usually relies on other Application Layer protocols, most notably Hypertext Transfer Protocol
(HTTP) or Simple Mail Transfer Protocol (SMTP), for message negotiation and transmission.

SOAP is an XML-based protocol to let applications exchange information over HTTP.


Or more simple: SOAP is a protocol for accessing a Web Service.

SOAP stands for Simple Object Access Protocol

SOAP is a communication protocol

SOAP is a format for sending messages

SOAP is designed to communicate via Internet

SOAP is platform independent

SOAP is language independent

SOAP is based on XML

SOAP is simple and extensible

SOAP allows you to get around firewalls

SOAP is a W3C standard

RESTFull WebServices
32

Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport
protocols, the initial focus of SOAP is remote procedure calls transported via HTTP.
SOAP enables client applications to easily connect to remote services and invoke remote methods.
Other frameworks, including CORBA, DCOM, and Java RMI, provide similar functionality to SOAP, but SOAP
messages are written entirely in XML and are therefore uniquely platform- and language-independent.

Why SOAP?
It is important for application development to allow Internet communication between programs.
Today's applications communicate using Remote Procedure Calls (RPC) between objects like DCOM and CORBA,
but HTTP was not designed for this. RPC represents a compatibility and security problem; firewalls and proxy servers
will normally block this kind of traffic.
A better way to communicate between applications is over HTTP, because HTTP is supported by all Internet browsers
and servers. SOAP was created to accomplish this.
SOAP provides a way to communicate between applications running on different operating systems, with different
technologies and programming languages.

History
SOAP was designed as an object-access protocol in 1998 by Dave Winer, Don Box, Bob Atkinson, and Mohsen AlGhosein for Microsoft, where Atkinson and Al-Ghosein were working at the time. The SOAP specification is currently
maintained by the XML Protocol Working Group of the World Wide Web Consortium.
SOAP originally stood for 'Simple Object Access Protocol' but this acronym was dropped with Version 1.2 of the
standard. Version 1.2 became a W3C recommendation on June 24, 2003. The acronym is sometimes confused with
SOA, which stands for Service-oriented architecture, but the acronyms are unrelated.
After SOAP was first introduced, it became the underlying layer of a more complex set of Web Services, based on
Web Services Description Language (WSDL) and Universal Description Discovery and Integration (UDDI). These
services, especially UDDI, have proved to be of far less interest, but an appreciation of them gives a more complete
understanding of the expected role of SOAP compared to how web services have actually evolved.

SOAP Message Structure


Posted by Dinesh Rajput

RESTFull WebServices
33

A SOAP message is an ordinary XML document containing the following elements.

Envelope: ( Mandatory )
Defines the start and the end of the message.

Header: ( Optional )
Contains any optional attributes of the message used in processing the message, either at an intermediary point or at
the ultimate end point.

Body: ( Mandatory )
Contains the XML data comprising the message being sent.

Fault: ( Optional )
An optional Fault element that provides information about errors that occurred while processing the message
All these elements are declared in the default namespace for the SOAP envelope:
http://www.w3.org/2001/12/soap-envelope
and the default namespace for SOAP encoding and data types is:
http://www.w3.org/2001/12/soap-encoding
NOTE: All these specifications are subject to change. So keep updating yourself with the latest specifications
available W3 website.

Syntax Rules

Here are some important syntax rules:


A SOAP message MUST be encoded using XML

A SOAP message MUST use the SOAP Envelope namespace

A SOAP message MUST use the SOAP Encoding namespace

A SOAP message must NOT contain a DTD reference

A SOAP message must NOT contain XML Processing Instructions

A SOAP Message Structure1.


2.
3.
4.

<?xml version="1.0"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"
SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

RESTFull WebServices
34

5.
6.
7.
8.
9.

<SOAP-ENV:Header>
...
...
</SOAP-ENV:Header>

10.
11.

<SOAP-ENV:Body>

12.
13.
14.
15.
16.
17.
18.
19.

...
...
<SOAP-ENV:Fault>
...
...
</SOAP-ENV:Fault>
</SOAP-ENV:Body>

20.
21.

</SOAP_ENV:Envelope>

RESTFull WebServices
35

You might also like