7551207b9d54a4c7939f071ed1187189

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 45

REST

by Jeevan
Jagadeesh
REpresentational State Transfer
(REST)

Definition of REST -

“REST is an architectural style built on


certain principles using the "Web"
fundamentals”
Features of the Web

 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
Fundamental Aspects of the
REST

 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.
Resources
 HTTP Standard Methods
Communicate with a standard set of methods

URIs Simple Operations


Constraints of REST

 Uniform interface
 Decoupled client-server interaction
 Stateless
 Cacheable
 Layered
 Code on Demand (optional)
Why is it called
"Representational State Transfer? "

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.
REST Actions

 6 HTTP behaviors associated with REST


actions
 GET
 POST
 PUT
 DELETE
 OPTIONS
 HEAD
GET

 GET - query/read a resource for a representation


POST

 POST - Create a resource with ID set by server


Remaining Actions

 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
JAVA and REST

 Java has defined JAX-RS (JSR 311) as the Java API for
RESTful Web Services
Popular Java Rest
implementations

 Jersey --- Sun/ Oracle


 RESTEasy --- JBOSS
 CXF --- Apache
Hello World Demo

 Create a Dynamic Web Project


 Place the below jars in WEB-INF/lib
Configuring the Servlet
Create Resource/Service
Testing the Resource
Binding URI

 @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
CRUD using HTTP Method
Annotations

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
Representation Annotations

@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
How it Works?
Scanning/Loading only the
required packages

web.xml

<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.rest</param-value>
</init-param>
Demo

Lets Build a Rest based application to perform CRUD


operations using the HTTP method and representation
annotations.
CRUD Testing

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
Sub-Resource Locators

 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


JAX-RS Injection

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
@PathParam

@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) {…}
@QueryParam

@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
@MatrixParam

@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
@FormParam

@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
@HeaderParam

@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
@CookieParam

@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
JAX RS and JAXB

 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-JAXB Example

@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
JAXB and JSON

 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
Default Response

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
Customizing Response with
Response Class

 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();
Exception Handling

 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);
}
Custom Exception Handling
using ExceptionMapper

 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
Content Negotiation

 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.
Conneg Continued
 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
JAX-RS Conneg using JAXB

 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);
}
HATEOAS

 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 - Example

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>


<customers>
<customer id="1">
<first-name>Jeevan</first-name>
<last-name>Jagadeesh</last-name>
<city>Bangalore</city>
</customer>
<customer id="2">
<first-name>Test</first-name>
<last-name>TestLast</last-name>
<city>Mysore</city>
</customer>
</customers>
REST VS SOAP

TYPE REST SOAP


Specification JAX-RS JAX-WS
Language and Yes Yes
Platform
Independence
Transport protocol HTTP HTTP, SMTP, JMS
Message Size Lightweight, no extra xml Heavy, has SOAP
markup specific markup
Message XML, JSON, other valid XML
Communication MIME type
Caching GET operations can be No
cached
Thank You

You might also like