[go: up one dir, main page]

0% found this document useful (0 votes)
87 views9 pages

Rest Vs Soap

The document compares REST and SOAP web service architectures. SOAP uses WSDL contracts and XML formatting, while REST uses HTTP methods and URIs to expose resources without a contract. REST services are generally easier to maintain and require less bandwidth since they can use lightweight formats like JSON. Key aspects of REST include representing resources, using HTTP request/response messages, addressing resources with URIs, and having a stateless and cacheable interface.

Uploaded by

Diana Cobelea
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views9 pages

Rest Vs Soap

The document compares REST and SOAP web service architectures. SOAP uses WSDL contracts and XML formatting, while REST uses HTTP methods and URIs to expose resources without a contract. REST services are generally easier to maintain and require less bandwidth since they can use lightweight formats like JSON. Key aspects of REST include representing resources, using HTTP request/response messages, addressing resources with URIs, and having a stateless and cacheable interface.

Uploaded by

Diana Cobelea
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

REST vs SOAP

Parameter SOAP REST


Acronym SOAP stands for simple object access REST stands for REpresentational
protocol State Transfer

Protocol vs  SOAP is a standard protocol to create web Rest is architectural style to


Architectural style services create web services.

Contract Client and Server are bind with WSDL There is no contract between
contract client and Server.
Format Support SOAP supports only XML format REST web services supports XML,
json and plain text etc.
Maintainability SOAP web services are hard to maintain as REST web services are generally
if we do any changes in WSDL , we need to easy to maintain.
create client stub again
Service interfaces vs SOAP uses Service interfaces to expose Rest uses URI to
URI business logic expose business logic

Security SOAP has its own security : WS-security Rest inherits its security from
underlying transport layer.
Bandwidth SOAP requires more bandwidth and REST requires less bandwith and
resources as it uses XML messages to resources. It can use JSON also.
exchange information
Learning curve SOAP web services are hard to learn as you REST web services are easy to
need to understand WSDL , client stub understand as you need to
annotate plain java class with
JAX-RS annotations to use
various HTTP methods.

While REST stands for Representational State Transfer, which is an architectural style for networked
hypermedia applications, it is primarily used to build Web services that are lightweight, maintainable,
and scalable. A service based on REST is called a RESTful service. REST is not dependent on any protocol,
but almost every RESTful service uses HTTP as its underlying protocol. In this article, I examine the
creation of RESTful services with HTTP.

Features of a RESTful Services


Every system uses resources. These resources can be pictures, video files, Web pages, business
information, or anything that can be represented in a computer-based system. The purpose of a service
is to provide a window to its clients so that they can access these resources. Service architects and
developers want this service to be easy to implement, maintainable, extensible, and scalable. A RESTful
design promises that and more. In general, RESTful services should have following properties and
features, which I'll describe in detail:

Representations
Messages
URIs
Uniform interface
Stateless
Links between resources
Caching

Representations
The focus of a RESTful service is on resources and how to provide access to these resources. A resource
can consist of other resources. While designing a system, the first thing to do is identify the resources
and determine how they are related to each other. This is similar to the first step of designing a
database: Identify entities and relations. Once we have identified our resources, the next thing we need
is to find a way to represent these resources in our system. You can use any format for representing the
resources, as REST does not put a restriction on the format of a representation. For example, depending
on your requirement, you can decide to use JSON or XML. If you are building Web services that will be
used by Web pages for AJAX calls, then JSON is a good choice. XML can be used to represent more
complex resources. In fact, you can use more than one format and decide which one to use for a
response depending on the type of client or some request parameters. Whichever format you use, a
good representation should have some obvious qualities:
- Both client and server should be able to comprehend this format of representation.
- A representation should be able to completely represent a resource. If there is a need to partially
represent a resource, then you should think about breaking this resource into child resources. Dividing
big resources into smaller ones also allows you to transfer a smaller representation. Smaller
representations mean less time required to create and transfer them, which means faster services.
- The representation should be capable of linking resources to each other. This can be done by placing
the URI or unique ID of the related resource in a representation (more on this in the coming sections).

Messages
The client and service talk to each other via messages. Clients send a request to the server, and the
server replies with a response. Apart from the actual data, these messages also contain some metadata
about the message. It is important to have some background about the HTTP 1.1 request and response
formats for designing RESTful Web services.

HTTP Request - has five major parts:


Verb − Indicate HTTP methods such as GET, POST, DELETE, PUT etc.
URI − Uniform Resource Identifier (URI) to identify the resource on server.
HTTP Version − Indicate HTTP version, for example HTTP v1.1 .
Request Header − Contains metadata for the HTTP Request message as key-value pairs. For example,
client ( or browser) type, format supported by client, format of message body, cache settings etc.
Request Body − Message content or Resource representation.

HTTP Response – has four major parts:


Status/Response Code − Indicate Server status for the requested resource. For example 404 means
resource not found and 200 means response is ok.
HTTP Version − Indicate HTTP version, for example HTTP v1.1 .
Response Header − Contains metadata for the HTTP Response message as key-value pairs. For example,
content length, content type, response date, server type etc.
Response Body − Response message content or Resource representation.
200 –OK
201 - CREATED, when a resource is successful created using POST or PUT request. Return link to newly
created resource using location header.
204 - NO CONTENT, when response body is empty for example, a DELETE request.
304 - NOT MODIFIED, used to reduce network bandwidth usage in case of conditional GET requests.
Response body should be empty. Headers should have date, location etc.
400 - BAD REQUEST, states that invalid input is provided e.g. validation error, missing data.
401 - FORBIDDEN, states that user is not having access to method being used for example, delete access
without admin rights.
404 - NOT FOUND, states that method is not available.
409 - CONFLICT, states conflict situation while executing the method for example, adding duplicate
entry.
500 - INTERNAL SERVER ERROR, states that server has thrown some exception while executing the
method.

Addressing Resources
REST requires each resource to have at least one URI. A RESTful service uses a directory hierarchy like
human readable URIs to address its resources. The job of a URI is to identify a resource or a collection of
resources. The actual operation is determined by an HTTP verb. The URI should not say anything about
the operation or action. This enables us to call the same URI with different HTTP verbs to perform
different operations.
Suppose we have a database of persons and we wish to expose it to the outer world through a service. A
resource person can be addressed like this: http://MyService/Persons/1
This URL has following format: Protocol://ServiceName/ResourceType/ResourceID
Here are some important recommendations for well-structured URIs:
 Use plural nouns for naming your resources.
 Avoid using spaces as they create confusion. Use an _ (underscore) or – (hyphen) instead.
 A URI is case insensitive. I use camel case in my URIs for better clarity. You can use all lower-case
URIs.
 You can have your own conventions, but stay consistent throughout the service. Make sure your
clients are aware of this convention. It becomes easier for your clients to construct the URIs
programmatically if they are aware of the resource hierarchy and the URI convention you follow.
 A cool URI never changes; so give some thought before deciding on the URIs for your service. If
you need to change the location of a resource, do not discard the old URI. If a request comes for
the old URI, use status code 300 and redirect the client to the new location.
 Avoid verbs for your resource names until your resource is actually an operation or a process.
Verbs are more suitable for the names of operations. For example, a RESTful service should not
have the URIs http://MyService/FetcthPerson/1 or http://MyService/DeletePerson?id=1.

Query Parameters in URI


The preceding URI is constructed with the help of a query parameter: http://MyService/Persons?id=1
The query parameter approach works just fine and REST does not stop you from using query
parameters. However, this approach has a few disadvantages.
- Increased complexity and reduced readability, which will increase if you have more parameters
- Search-engine crawlers and indexers like Google ignore URIs with query parameters. If you are
developing for the Web, this would be a great disadvantage as a portion of your Web service will be
hidden from the search engines.
The basic purpose of query parameters is to provide parameters to an operation that needs the data
items. For example, if you want the format of the presentation to be decided by the client. You can
achieve that through a parameter like this:
http://MyService/Persons/1?format=xml&encoding=UTF8
or http://MyService/Persons/1?format=json&encoding=UTF8
Including the parameters format and encoding here in the main URI in a parent-child hierarchy will not
be logically correct as they have no such relation: http://MyService/Persons/1/json/UTF8
Query parameters also allow optional parameters. This is not otherwise possible in a URI. You should
use query parameters only for the use they are intended for: providing parameter values to a process.

Uniform Interface
RESTful systems should have a uniform interface. HTTP 1.1 provides a set of methods, called verbs, for
this purpose. Among these the more important verbs are:
Method Operation performed on server Quality
GET Read a resource. Safe
PUT Insert a new resource or update if the resource Idempotent
already exists.
POST Insert a new resource. Also can be used to N/A
update an existing resource.
DELETE Delete a resource . Idempotent
OPTIONS List the allowed operations on a resource. Safe
HEAD Return only the response headers and no Safe
response body.
A Safe operation is an operation that does not have any effect on the original value of the resource. For
example, the mathematical operation "divide by 1" is a safe operation because no matter how many
times you divide a number by 1, the original value will not change. An Idempotent operation is an
operation that gives the same result no matter how many times you perform it. For example, the
mathematical operation "multiply by zero" is idempotent because no matter how many times you
multiply a number by zero, the result is always same. Similarly, a Safe HTTP method does not make any
changes to the resource on the server. An Idempotent HTTP method has same effect no matter how
many times it is performed. Classifying methods as Safe and Idempotent makes it easy to predict the
results in the unreliable environment of the Web where the client may fire the same request again.

GET is probably the most popular method on the Web. It is used to fetch a resource.
HEAD returns only the response headers with an empty body. This method can be used in a scenario
when you do not need the entire representation of the resource. For example, HEAD can be used to
quickly check whether a resource exists on the server or not.
The method OPTIONS is used to get a list of allowed operations on the resource. For example consider
the request:
OPTIONS http://MyService/Persons/1
HTTP/1.1
HOST: MyService
The service after authorizing and authenticating the request can return something like:
200 OK
Allow: HEAD, GET,
PUT
The second line contains the list of operations that are allowed for this client.
Difference between PUT and POST
The key difference between PUT and POST is that PUT is idempotent while POST is not. No matter how
many times you send a PUT request, the results will be same. POST is not an idempotent method.
Making a POST multiple times may result in multiple resources getting created on the server.
Another difference is that, with PUT, you must always specify the complete URI of the resource. This
implies that the client should be able to construct the URI of a resource even if it does not yet exist on
the server. This is possible when it is the client's job to choose a unique name or ID for the resource, just
like creating a user on the server requires the client to choose a user ID. If a client is not able to guess
the complete URI of the resource, then you have no option but to use POST.
Request Operation
PUT http://MyService/Persons/ Won't work. PUT requires a complete URI
PUT http://MyService/Persons/1 Insert a new person with PersonID=1 if it does not already
exist, or else update the existing resource
POST http://MyService/Persons/ Insert a new person every time this request is made and
generate a new PersonID.
POST http://MyService/Persons/1 Update the existing person where PersonID=1
It is clear from the above table that a PUT request will not modify or create more than one resource no
matter how many times it is fired (if the URI is same). There is no difference between PUT and POST if
the resource already exists, both update the existing resource. The third request (POST
http://MyService/Persons/) will create a resource each time it is fired. A lot of developers think that
REST does not allow POST to be used for update operation; however, REST imposes no such restrictions.

Statelessness
A RESTful service is stateless and does not maintain the application state for any client. A request cannot
be dependent on a past request and a service treats each request independently. HTTP is a stateless
protocol by design and you need to do something extra to implement a stateful service using HTTP. But
it is really easy to implement stateful services with current technologies. We need a clear understanding
of a stateless and stateful design so that we can avoid misinterpretation.
A stateless design looks like so:
Request1: GET http://MyService/Persons/1 HTTP/1.1
Request2: GET http://MyService/Persons/2 HTTP/1.1
Each of these requests can be treated separately.
A stateful design, on the other hand, looks like so:
Request1: GET http://MyService/Persons/1 HTTP/1.1
Request2: GET http://MyService/NextPerson HTTP/1.1
To process the second request, the server needs to remember the last PersonID that the client fetched.
In other words, the server needs to remember the current state — otherwise Request2 cannot be
processed. Design your service in a way that a request never refers to a previous request. Stateless
services are easier to host, easy to maintain, and more scalable. Plus, such services can provide better
response time to requests, as it is much easier to load balance them.
Advantages
- Web services can treat each method request independently.
- Web services need not to maintain client's previous interactions. It simplifies application design.
- As HTTP is itself a statelessness protocol, RESTful Web services work seamlessly with HTTP protocol.
Disadvantage: Web services need to get extra information in each request and then interpret to get the
client's state in case client interactions are to be taken care of.

Links Between Resources


A resource representation can contain links to other resources like an HTML page contains links to other
pages. The representations returned by the service should drive the process flow as in case of a website.
When you visit any website, you are presented with an index page. You click one of the links and move
to another page and so on. Here, the representation is in the HTML documents and the user is driven
through the website by these HTML documents themselves. The user does not need a map before
coming to a website. A service can be (and should be) designed in the same manner. Let's consider the
case in which a client requests one resource that contains multiple other resources. Instead of dumping
all these resources, you can list the resources and provide links to them. Links help keep the
representations small in size.
<Club>
<Name>Authors Club</Name>
<Persons>
<Person>
<Name>M. Vaqqas</Name>
<URI>http://MyService/Persons/1</URI>
</Person>
<Person>
<Name>S. Allamaraju</Name>
<URI>http://MyService/Persons/12</URI>
</Person>
</Persons>
</Club>
Caching refers to storing server response in client itself so that a client needs not to make server request
for same resource again and again. A server response should have information about how a caching is to
be done so that a client caches response for a period of time or never caches the server response.
Header Application
Date Date and time when this representation was generated.
Last Modified Date and time when the server last modified this representation.
Cache-Control The HTTP 1.1 header used to control caching.
Expires Expiration date and time for this representation. To support HTTP 1.0 clients.
Age Duration passed in seconds since this was fetched from the server. Can be
inserted by an intermediary component.
Values of these headers can be used in combination with the directives in a Cache-Control header to
check if the cached results are still valid or not. The most common directives for Cache-Control header
are:
Directive Application
Public The default. Indicates any component can cache this representation.
Private Intermediary components cannot cache this representation, only client or server can do so.
no-cache/no-store Caching turned off.
max-age Duration in seconds after the date-time marked in the Date header for which this representation is
valid.
s-maxage Similar to max-age but only meant for the intermediary caching.
must-revalidate Indicates that the representation must be revalidated by the server if max-age has passed.
proxy-validate Similar to max-validate but only meant for the intermediary caching.
You have seen some of these headers and directives above in Listing Five. Depending on the nature of
the resources, a service can decide the values of these headers and directives. For example, a service
providing stock market updates would keep the cache age limit to as low as possible or even turn off
caching completely as this is a critical information and users should get the latest results all the time. On
the other hand, a public picture repository whose contents do not change so frequently would use a
longer caching age and slack caching rules. The server, the client, and any intermediate component
between them should follow these directives to avoid outdated information getting served.
- Always keep static contents like images, css, JavaScript cacheable, with expiration date of 2 to 3 days.
- Never keep expiry date too high.
- Dynamic contents should be cached for few hours only.

WSDL (Web Service Description Language) – pentru SOAP. It is an XML file that describes the technical
details of how to implement a web service, more specifically the URI, port, method names, arguments,
and data types. You can understand following details using WSDL
Port / Endpoint – URL of the web service
Input message format
Output message format
Security protocol that needs to be followed
Which protocol the web service uses
wsimport – utilitar care genereaza clase Java din WSDL
WADL (Web Application Description Language)– similar cu WSDL, dar specializat pe REST
Testing web services: Postman for chrome browser, Poster for firefox
Frameworks to implement REST: Jersey, Restlet, EasyRest, etc.
Jersey is open source framework for developing RESTful Web Services in Java that provides support for
JAX-RS APIs. Its advantages are:
- contains support for Web Application Description Language (WADL); 
- contains Jersey Test Framework which lets run and test Jersey REST services inside JUnit;   
- supports for the REST MVC pattern, which would allow to return a View from Jersey services rather
than just data.

Ajax vs REST
- in Ajax, the request are sent to the server by using XMLHttpRequest objects; REST have a URL structure
and a request/response pattern the revolve around the use of resources;
- Ajax eliminates the interaction between the customer and server asynchronously; REST requires the
interaction between the customer and server;
- Ajax is a set of technology; REST is a type of software architecture and a method for users to request
data or information from servers.

JAX-WS - SOAP
JAX-RS este un JAVA API pentru crearea de servicii web REST. JAX-RS pune la dispoziția programatorului
o serie de adnotări prin care ajută la dezvoltarea de clienți și la expunerea serviciilor web. De asemenea,
conține toate specificațiile despre cum ar trebui implementate serviciile. Folosind aceste unelte putem
mapa o clasă simplă Java (POJO – plain old java object) ca o resursă web.
Jersey este implementarea oficială a JAX-RS în Java. Cu alte cuvinte, JAX-RS definește cum ar trebui
implementate serviciile web, iar Jersey conține aceste implementări bazate pe specificațiile JAX-RS. Un
proiect web care conține servicii web are nevoie să depindă atât de bibliotecile JAX-RS cât și de
bibliotecile Jersey. Acest lucru este necesar deoarece JAX-RS pune la dispoziție un set de interfețe care
sunt implementate în Jersey.
JAX-RS Annotations
Root resource classes are POJOs (Plain Old Java Objects) that are annotated with @Path have at least
one method annotated with @Path or a resource method designator annotation such as @GET, @PUT,
@POST, @DELETE.

@Path – adnotarea face asocierea dintre un URI si o metoda. In URI pot fi folosite si variabile cuprinse
intre { } care vor fi substituite la runtime cu o anumita valoare si care va fi accesata folosind in signature
metodei adnotarea @PathParam. Pentru aceste variabile se pot pune si unele conditii, de exemplu sa
contina doar litere, iar in caz contrar, raspunsul va fi 404 Not Found. Nu conteaza daca valuarea din
@Path incepe, se termina sau nu cu /.
@Path("/users/{username}")
public class UserResource {
 
    @GET
    @Produces("text/xml")
    public String getUser(@PathParam("username") String userName) {
        ...
    }
}
@Consumes – folosind această adnotare putem specifica tipul conținutului (cunoscut și ca tipul media
sau MIME) răspunsului care va fi acceptat de către resursă – pot fi mai multe tipuri
@Produces – folosind această adnotare putem specifica tipul conținutului (cunoscut și ca tipul media sau
MIME) răspunsului care va fi returnat către client – pot fi mai multe tipuri
@GET
@Produces({"application/xml; qs=0.9", "application/json"})
public String doGetAsXmlOrJson() {
    ...
}
In the above sample, if client accepts both "application/xml" and "application/json" (equally), then a
server always sends "application/json", since "application/xml" has a lower quality factor.

@QueryParam- extragerea parametrilor din cererea HTTP


@Path("smooth")
@GET
public Response smooth(
    @DefaultValue("2") @QueryParam("step") int step,
    @DefaultValue("true") @QueryParam("min-m") boolean hasMin,
    @DefaultValue("true") @QueryParam("max-m") boolean hasMax,
    @DefaultValue("true") @QueryParam("last-m") boolean hasLast,
    @DefaultValue("blue") @QueryParam("min-color") ColorParam minColor,
    @DefaultValue("green") @QueryParam("max-color") ColorParam maxColor,
    @DefaultValue("red") @QueryParam("last-color") ColorParam lastColor) {
 }
@FormParam is slightly special because it extracts information from a request representation that is of
the MIME media type "application/x-www-form-urlencoded" and conforms to the encoding specified by
HTML forms. It’s very useful for extracting information that is POSTed by HTML forms, for example the
following extracts the form parameter named "name" from the POSTed form data:
@POST
@Consumes("application/x-www-form-urlencoded")
public void post(@FormParam("name") String name) {
    // Store the message
}
If it is necessary to obtain a general map of parameter name to values then, for query and path
parameters it is possible to do the following:
@GET
public String get(@Context UriInfo ui) {
    MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
    MultivaluedMap<String, String> pathParams = ui.getPathParameters();
}

You might also like