Rest Vs Soap
Rest Vs Soap
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.
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.
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.
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.
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.