3. Web is matured and widely accepted http protocol
HTTP protocol has standard methods like GET, POST,
PUT ,DELETE
HTTP protocol is stateless
Uses URI (uniform resource identifier) using which we
can identify any resource on the web
Features of the Web
4. Resources
Every distinguishable entity is a resource. A resource may be a Web site,
an HTML page, an XML document, a Web service, a physical device, etc.
URIs to Identify Resources
Every resource is uniquely identified by a URL.
HTTP Standard Methods
Communicate with a standard set of methods
Fundamental Aspects of the REST
Resources
URIs Simple Operations
6. The Client request a resource using a URL.
A representation of the resource is returned (in this case as an HTML document).
The representation (e.g., Boeing747.html) places the client in a new state.
When the client selects a hyperlink in Boeing747.html, it accesses another
resource.
The new representation places the client application into yet another state.
Thus, the client application transfers state with each resource representation.
Why is it called
"Representational State Transfer? "
7. 6 HTTP behaviors associated with REST actions
GET
POST
PUT
DELETE
OPTIONS
HEAD
REST Actions
8. GET - query/read a resource for a representation
GET
9. POST - Create a resource with ID set by server
POST
10. PUT - Update a resource, ID specified by the client
DELETE - Remove the Resource
HEAD – Returns meta information about the request
URL
OPTIONS – Indicates which HTTP methods are
supported at the request URL
Remaining Actions
11. Java has defined JAX-RS (JSR 311) as the Java API for
RESTful Web Services
JAVA and REST
12. Jersey --- Sun/ Oracle
RESTEasy --- JBOSS
CXF --- Apache
Popular Java Rest implementations
13. Create a Dynamic Web Project
Place the below jars in WEB-INF/lib
Hello World Demo
17. @javax.ws.rs.Path annotation is used to define a URI
matching pattern for incoming HTTP requests
@Path can be placed at class level or at method level
To make a Java class a Resource, it must be @Path
annotated at class level and should have at least one
method Path annotated. These types of classes are called
Root Resources
Binding URI
18. JAX-RS defines 4 annotations that map to specific
HTTP operations:
@javax.ws.rs.GET
@javax.ws.rs.PUT
@javax.ws.rs.POST
@javax.ws.rs.DELETE
CRUD using HTTP Method
Annotations
19. @javax.ws.rs.Produces
Used to specify the MIME media types of representations a
resource can produce and send back to the client
Can be applied at both the class and method levels
Method level overrides class level
@javax.ws.rs.Consumes
Used to specify the MIME media types of representations a
resource can consume
Can be applied at both the class and method levels
Method level override a class level
Representation Annotations
22. Lets Build a Rest based application to perform CRUD
operations using the HTTP method and representation
annotations.
Demo
23. Sample Xml:
<?xml version="1.0" encoding="UTF-8"?>
<customer>
<first-name>Jeevan</first-name>
<last-name>Jagadeesh</last-name>
<city>Bangalore</city>
</customer>
Test Scenario’s:
1. Create customers using POST method
2. Retrieve the customers using GET with id
3. Update a customer
4. Retrieve the updated customer
5. Delete a customer
6. Do a get on the deleted customer
CRUD Testing
24. Sub-resource locators are Java methods annotated with
@Path, but with no HTTP method annotation
Sub-resource locators enable reuse of resource classes
Sub-resource locators supports polymorphism (The
processing of resource class returned by sub-resource
locators is performed at runtime)
Lets try an example
Sub-Resource Locators
25. JAX-RS has provided a set of injection annotations, through
which we can retrieve data from the request.
@javax.ws.rs.PathParam
@javax.ws.rs.MatrixParam
@javax.ws.rs.QueryParam
@javax.ws.rs.FormParam
@javax.ws.rs.HeaderParam
@javax.ws.rs.CookieParam
JAX-RS Injection
26. @PathParam annotation is used to extract values from URI parameters
@GET // GET /customers/1
@Path("{id}")
public void getCustomer(@PathParam("id") int id) {
System.out.println("In get Customer---id===" + id);
}
Multiple Path Param
@GET // GET /customers/Jeevan-Jagadeesh
@Path("{first:[a-zA-Z]+}-{last:[a-zA-Z]+}")
@Produces("application/xml")
public StreamingOutput getCustomerUsingFirstLast(
@PathParam("first") String first, @PathParam("last") String last) {…}
@PathParam
27. @QueryParam annotation is used to inject URI query parameter into Java
method
@Path("/customers")
public class CustomerResource {
@GET
public void getCustomers(@QueryParam("start") int start,
@QueryParam("end") int end) {
System.out.println("Start " + start);
System.out.println("End " + end);
}
}
URI - /customers?start=0&end=10
@QueryParam
28. @MatrixParam annotation is used to inject name value pair in the URI path
into Java method
Matrix parameters must be separate by a semi colon
@GET
@Path("/matrix")
public Response testMatrixParam(@MatrixParam("firstName") String firstName,
@MatrixParam("lastName") String lastName) {
System.out.println("firstName " + firstName);
System.out.println("lastName" + lastName);
return Response.status(200).entity("In Matrix Param firstName: " +firstName + " lastName:
"+lastName).build();
}
URI - matrix;firstName=Jeevan;lastName=Jagadeesh
@MatrixParam
29. @FormParam annotation to bind HTML form parameters value to a Java
method
@POST
@Path("/formParam")
public Response formParam(@FormParam("firstname") String firstname,
@FormParam("lastname") String lastname) {
return Response.status(200).entity(
"In Form Param, firstname : " + firstname + ", lastname : "
+ lastname).build();
}
URI - /customers/formParam
POST Method, content-type=application/x-www-form-urlencoded,
HTTP Body = firstname=Jeevan
lastName=Jagadeesh
@FormParam
30. @HeaderParam annotation is used to inject HTTP request header
values.
@GET
@Path("/headerParam")
public Response headerParam(@HeaderParam("user-agent") String userAgent) {
return Response.status(200).entity("In Header Param userAgent : " + userAgent)
.build();
}
URI - /customers/headerParam
@HeaderParam
31. @CookieParam annotation allows you to inject cookies sent by a
client request into your JAX-RS resource methods
Servers can store state information in cookies on the client, and can retrieve that
information when the client makes its next request
@CookieParam
32. Java API for XML binding (JAXB) – converting xml to java
objects (unmarshalling) and vice-versa (marshalling)
JAX-RS has built-in support for JAXB
The JAX-RS has built-in handlers to support marshalling and
unmarshalling of classes that are annotated with
@XmlRootElement
JAX RS and JAXB
33. @XmlRootElement(name = "customer")
public class Customer {
}
Annotating the POJO object, JAX-RS does marshalling and unmarshalling
without us writing any code.
Note : The Media type must be
• application/xml
• text/xml
• application/*+xml
JAX RS-JAXB Example
34. Using JAXB we can to convert Java objects to JSON
For this we need jersey-json-1.10.jar to be placed in the WEB-
INF/lib folder
JAXB and JSON
35. JAX-RS returns default response codes
Successful Response:
Successful HTTP response code numbers range from 200 to 399
• GET returns 200 OK
• POST returns 201 CREATED
• 200 OK
• 201 Created
• 202 Accepted
• 203 Non-Authoritative Information
• 204 No Content
• 205 Reset Content
• 206 Partial Content
Error Response:
Error response code numbers range from 400 to 599
• 404 Not Found
• 405 Method Not allowed
• 406 Not Acceptable
Default Response
36. Sometimes it is necessary to return additional information in response to a HTTP
request. Such information can be built and returned using
• Response
• Response.ResponseBuilder
Response building provides other functionality such as
• setting the entity tag
• last modified date of the representation.
Response.status(201).entity("Customer with id : " + cust.getId() + "
Created").build();
Customizing Response with Response
Class
37. JAX-RS provides javax.ws.rs.WebApplicationException.
Extends java.lang.RuntimeException
When WebApplicationException is thrown, jax-rs catches the exception
returns the Response back to the client
Any other exception will result in HTTP status “500 Internal Server Error”
if (customer== null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
Exception Handling
38. There could be various exceptions thrown from application code and third-
party frameworks. Catching and then wrapping all these exceptions within
WebApplicationException would become quite tedious
Alternatively we can implement javax.ws.rs.ext.ExceptionMapper for the
exception type you want to handle.
ExceptionMapper implementation class must be annotated with the
@Provider annotation
toResponse()method receives the thrown exception and creates a Response
object that will be used to build the HTTP response
Custom Exception Handling using
ExceptionMapper
39. DATA Format Problems:
• Different clients need different formats to run efficiently. E.g: Java clients might
like their data within an XML format. Ajax clients work a lot better with JSON
• Clients may also want internationalized data
HTTP Solution:
• Http client's have the capability to specify to the server how it would like its
response formatted. i.e The client can negotiate the content type of the data, how
it should be encoded
• This protocol is called HTTP Content Negotiation or conneg.
Content Negotiation
40. Content Type Negotiation:
• Clients set an Accept request header that is a comma-delimited list of preferred
formats.
For example:
GET http://localhost:8080/App/customers
Accept: application/xml, application/json
Language Negotiation:
• Clients use the Accept-Language header to specify the language they would like
to receive.
For example:
GET http://localhost:8080/App/customers
Accept-Language: en-us, es, fr
Conneg Continued
41. Content Type Negotiation:
• As seen in previous examples, we could used the @Produce annotation
Language Negotiation:
• Unfortunately, JAX-RS does not have the annotation of @ProduceLanguages
• JAX-RS has exposed HttpHeaders Api, using which we can get the Accept-
Language value
public void get(@Context HttpHeaders headers) {
Locale language = headers.getAcceptableLanguages().get(0);
System.out.println("Lan " +language);
}
JAX-RS Conneg using JAXB
42. HATEOAS stands for Hypermedia As The Engine Of Application State
The architectural principle that describes linking of URI is called
HATEOAS
To make it simple - providing hyperlinks, URIs in the representations
that clients can use to transition the Web service to new application
states
JAX-RS has the UriBuilder and UriInfo classes that makes it simple and
easy to build URIs
HATEOAS
44. TYPE REST SOAP
Specification JAX-RS JAX-WS
Language and
Platform
Independence
Yes Yes
Transport protocol HTTP HTTP, SMTP, JMS
Message Size Lightweight, no extra xml
markup
Heavy, has SOAP
specific markup
Message
Communication
XML, JSON, other valid MIME
type
XML
Caching GET operations can be cached No
REST VS SOAP
REST - uses the current features of the web in a simple and effective way by applying some principles.
Uniform interface
This is the API of the web service, describing operations and data structures.
It simplifies and decouples the architecture of both client and server, enabling each to evolve independently.
Client–server decoupling
Clients are separated from servers by a uniform interface.
For portability, clients must not concern themselves with data storage.
For simplicity and scalability, servers must not concern themselves with the UI or user state.
Servers and clients may be replaced and developed independently, as long as the interface is not altered.
Stateless
No client context should be store on the server between requests.
Each request contains all of the information necessary to service the request and session state is held in the client.
The server can be stateful, but server-side state must be addressable by URL as a resource.
This makes servers:
More scalable.
More visible for monitoring.
More reliable in the event of partial network failures
Cacheable
Clients may cache responses, so responses must define whether they are cachable to prevent clients reusing stale or inappropriate data in response to further requests.
Well-managed caching can eliminate repetitive client–server interactions, further improving scalability and performance.
Layered system
A client’s connection to a server may pass directly to the service or through several intermediaries, allowing:
Scalability by enabling load balancing and by providing shared caches
The enforcement of security policies.
Uniform interface
This is the API of the web service, describing operations and data structures.
It simplifies and decouples the architecture of both client and server, enabling each to evolve independently.
Client–server decoupling
Clients are separated from servers by a uniform interface.
The client-server constraint is based on a principle in software known as the separation of concerns.
Stateless
No client context should be store on the server between requests.
Each request contains all of the information necessary to service the request and session state is held in the client.
Cacheable
Clients may cache responses, so responses must define whether they are cacheable to prevent clients reusing stale or inappropriate data in response to further requests.
Well-managed caching can eliminate repetitive client–server interactions, further improving scalability and performance.
Layered system
REST architecture as hierarchical layers of components, limited to communication with their immediate neighbors
Code on Demand
Code on demand allows a client to download and execute code from a server.
Allows the client functionality to be extended after initial deployment of the application.
OPTIONS – Indicates which HTTP methods are supported at the request URL. Useful for identifying
HEAD – Same as GET but only returns meta-information about the resource. The response body will be empty. Useful for requesting information about a resource without having to request the resource itself.