Sabyasachi Ghosh, Senior Application Engneer Oracle India, @neilghosh Developing RESTful Web services with JAX-RS
Java API for RESTful Web Services (JAX-RS) Standard annotation-driven API that aims to help developers build RESTful Web services in Java
RESTful Application Cycle Resources are identified by URIs ↓ Clients communicate with resources via requests using a standard set of methods ↓ Requests and responses contain resource representations in formats identified by media types ↓ Responses contain URIs that link to further resources
Give everything an ID
Standard set of methods
Link things together
Multiple representations
Stateless communications
ID is a URI http://example.com/widgets/foo http://example.com/customers/bar http://example.com/customers/bar/orders/2 http://example.com/orders/101230/customer
Resources are identified by URIs Resource == Java class POJO
No required interfaces ID provided by  @Path  annotation Value is relative URI, base URI is provided by deployment context or parent resource
Embedded parameters for non-fixed parts of the URI
Annotate class or “sub-resource locator” method
Resources are identified by URIs @Path("orders/{order_id}") public class OrderResource {   @GET  @Path("customer") CustomerResource getCustomer( @PathParam(“order_id”)int id ) {...} }
Standard Set of Methods Purpose Method Remove DELETE Update or create with a known ID PUT Update or create without a known ID POST Read, possibly cached GET
Standard Set of Methods Annotate resource class methods with standard method @GET ,  @PUT ,  @POST ,  @DELETE ,  @HEAD
@HttpMethod  meta-annotation allows extensions, e.g. WebDAV JAX-RS routes request to appropriate resource class and method
Flexible method signatures, annotations on parameters specify mapping from request
Return value mapped to response
Standard Set of Methods @Path("properties/ {name} ") public class SystemProperty { @GET Property get(@PathParam(" name ") String name) {...} @PUT Property set(@PathParam(" name ") String name, String value ) {...} }
Parameters Template parameters and Regular expressions @Path("customers/ {firstname}-{lastname} ") @Path(" { id : \\d+} ") Matrix Parameters example.cars.com/mercedes/e55;color=black/2006 Query Paremetsrs DELETE /orders/233?cancel=true
Multiple Representations Offer data in a variety of formats XML
JSON
(X)HTML Maximize reach
Support content negotiation Accept header GET /foo Accept: application/json
URI-based GET /foo.json
Content Negotiation: Accept Header Accept: application/xml Accept: application/json;q=1.0, text/xml;q=0.5, application/xml;q=0.5, @GET @Produces({"application/xml","application/json"}) Order getOrder(@PathParam(" order_id ") String id) { ... } @GET @Produces("text/plain") String getOrder2(@PathParam("order_id") String id) { ... }
Content Negotiation: URL-based @Path("/orders") public class OrderResource { @Path("{orderId}.xml")    @Produces(“application/xml”)   @GET    public Order getOrderInXML(@PathParam("orderId") String orderId) { . . .   } @Path("{orderId}.json")    @Produces(“application/json”)   @GET   public Order getOrderInJSON(@PathParam("orderId") String orderId) { . . .   } }
Content Negotiation import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.PathParam; @Path("/actor/{id}") @GET @Produces("application/json") @PathParam("id") import javax.inject.Inject; import javax.enterprise.context.RequestScoped; @RequestScoped public class ActorResource { @Inject DatbaseBean db; public Actor getActor(  int id) { return db.findActorById(id); } }
Link Things Together <order self=&quot; http://example.com/orders/101230 &quot;> <customer ref=&quot; http://example.com/customers/bar &quot;> <product ref=&quot; http://example.com/products/21034 &quot;/> <amount value=&quot;1&quot;/> </order>
Responses Contain Links HTTP/1.1 201 Created Date: Wed, 03 Jun 2009 16:41:58 GMT Server: Apache/1.3.6 Location:  http://example.com/properties/foo Content-Type: application/order+xml Content-Length: 184 <property self=&quot; http://example.com/properties/foo &quot;> <parent ref=&quot; http://example.com/properties/bar &quot;/> <name>Foo</name> <value>1</value> </order>

RestFull Webservices with JAX-RS

  • 1.
    Sabyasachi Ghosh, SeniorApplication Engneer Oracle India, @neilghosh Developing RESTful Web services with JAX-RS
  • 2.
    Java API forRESTful Web Services (JAX-RS) Standard annotation-driven API that aims to help developers build RESTful Web services in Java
  • 3.
    RESTful Application CycleResources are identified by URIs ↓ Clients communicate with resources via requests using a standard set of methods ↓ Requests and responses contain resource representations in formats identified by media types ↓ Responses contain URIs that link to further resources
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
    ID is aURI http://example.com/widgets/foo http://example.com/customers/bar http://example.com/customers/bar/orders/2 http://example.com/orders/101230/customer
  • 10.
    Resources are identifiedby URIs Resource == Java class POJO
  • 11.
    No required interfacesID provided by @Path annotation Value is relative URI, base URI is provided by deployment context or parent resource
  • 12.
    Embedded parameters fornon-fixed parts of the URI
  • 13.
    Annotate class or“sub-resource locator” method
  • 14.
    Resources are identifiedby URIs @Path(&quot;orders/{order_id}&quot;) public class OrderResource { @GET @Path(&quot;customer&quot;) CustomerResource getCustomer( @PathParam(“order_id”)int id ) {...} }
  • 15.
    Standard Set ofMethods Purpose Method Remove DELETE Update or create with a known ID PUT Update or create without a known ID POST Read, possibly cached GET
  • 16.
    Standard Set ofMethods Annotate resource class methods with standard method @GET , @PUT , @POST , @DELETE , @HEAD
  • 17.
    @HttpMethod meta-annotationallows extensions, e.g. WebDAV JAX-RS routes request to appropriate resource class and method
  • 18.
    Flexible method signatures,annotations on parameters specify mapping from request
  • 19.
  • 20.
    Standard Set ofMethods @Path(&quot;properties/ {name} &quot;) public class SystemProperty { @GET Property get(@PathParam(&quot; name &quot;) String name) {...} @PUT Property set(@PathParam(&quot; name &quot;) String name, String value ) {...} }
  • 21.
    Parameters Template parametersand Regular expressions @Path(&quot;customers/ {firstname}-{lastname} &quot;) @Path(&quot; { id : \\d+} &quot;) Matrix Parameters example.cars.com/mercedes/e55;color=black/2006 Query Paremetsrs DELETE /orders/233?cancel=true
  • 22.
    Multiple Representations Offerdata in a variety of formats XML
  • 23.
  • 24.
  • 25.
    Support content negotiationAccept header GET /foo Accept: application/json
  • 26.
  • 27.
    Content Negotiation: AcceptHeader Accept: application/xml Accept: application/json;q=1.0, text/xml;q=0.5, application/xml;q=0.5, @GET @Produces({&quot;application/xml&quot;,&quot;application/json&quot;}) Order getOrder(@PathParam(&quot; order_id &quot;) String id) { ... } @GET @Produces(&quot;text/plain&quot;) String getOrder2(@PathParam(&quot;order_id&quot;) String id) { ... }
  • 28.
    Content Negotiation: URL-based@Path(&quot;/orders&quot;) public class OrderResource { @Path(&quot;{orderId}.xml&quot;) @Produces(“application/xml”) @GET public Order getOrderInXML(@PathParam(&quot;orderId&quot;) String orderId) { . . . } @Path(&quot;{orderId}.json&quot;) @Produces(“application/json”) @GET public Order getOrderInJSON(@PathParam(&quot;orderId&quot;) String orderId) { . . . } }
  • 29.
    Content Negotiation importjavax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.PathParam; @Path(&quot;/actor/{id}&quot;) @GET @Produces(&quot;application/json&quot;) @PathParam(&quot;id&quot;) import javax.inject.Inject; import javax.enterprise.context.RequestScoped; @RequestScoped public class ActorResource { @Inject DatbaseBean db; public Actor getActor( int id) { return db.findActorById(id); } }
  • 30.
    Link Things Together<order self=&quot; http://example.com/orders/101230 &quot;> <customer ref=&quot; http://example.com/customers/bar &quot;> <product ref=&quot; http://example.com/products/21034 &quot;/> <amount value=&quot;1&quot;/> </order>
  • 31.
    Responses Contain LinksHTTP/1.1 201 Created Date: Wed, 03 Jun 2009 16:41:58 GMT Server: Apache/1.3.6 Location: http://example.com/properties/foo Content-Type: application/order+xml Content-Length: 184 <property self=&quot; http://example.com/properties/foo &quot;> <parent ref=&quot; http://example.com/properties/bar &quot;/> <name>Foo</name> <value>1</value> </order>
  • 32.
    Responses Contain LinksUriInfo provides information about deployment context, the request URI and the route to the resource
  • 33.
    UriBuilder providesfacilities to easily construct URIs for resources
  • 34.
    Responses Contain Links@Context UriInfo i; SystemProperty p = ... UriBuilder b = i.getBaseUriBuilder(); URI u = b.path(SystemProperties.class) .path(p.getName()).build(); List<URI> ancestors = i.getMatchedURIs(); URI parent = ancestors.get(1);
  • 35.
    Responses Contain LinksUriBuilder builder = UriBuilder.fromPath(&quot;/customers/{id}&quot;); builder.scheme(&quot;http&quot;) .host(&quot;{hostname}&quot;) .queryParam(&quot;param={param}&quot;); http://{hostname}/customers/{id}?param={param} UriBuilder clone = builder.clone(); URI uri = clone.build(&quot;example.com&quot;, &quot;333&quot;, &quot;value&quot;); http://example.com/customers/333?param=value
  • 36.
    Response codes andException Successful HTTP : 200 to 399 200 – OK 204 – No Content Standard HTTP error : 400 to 599 404 – Not Found 406 - Not Acceptable 405 - Method Not Allowed java.lang.Exception java.lang.RuntimeException javax.ws.rs.WebApplicationException throw new WebApplicationException(Response.Status.NOT_FOUND);
  • 37.
  • 38.
  • 39.
    Everything required toprocess a request contained in the request
  • 40.
    Deployment JAX-RS applicationpackaged in WAR like a servlet
  • 41.
    For JAX-RS awarecontainers web.xml can point to Application subclass For non-JAX-RS aware containers web.xml points to implementation-specific Servlet ; and
  • 42.
    an init-param identifies the Application subclass Resource classes and providers can access Servlet request, context, config and response via injection
  • 43.
    JAX-RS 1.1 Integrationwith Java EE 6 – Servlets 3.0 No or Portable “web.xml” <web-app> <servlet> <servlet-name>Jersey Web Application</servlet-name> <servlet-class> com.sun.jersey.spi.container.servlet.ServletContainer </servlet-class> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>com.foo.MyApplication</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Jersey Web Application</servlet-name> <url-pattern>/ resources /*</url-pattern> </servlet-mapping> </web-app> public class MyApplication extends javax.ws.rs.core.Application { } @ApplicationPath(“resources”)
  • 44.
    JAX-RS Summary JavaAPI for building RESTful Web Services
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
    JAX-RS 1.1 JerseyClient-side API Consume HTTP-based RESTful Services
  • 50.
    Easy-to-use Better thanHttpURLConnection! Reuses JAX-RS API Resources and URI are first-class citizens Not part of JAX-RS yet com.sun.jersey.api.client
  • 51.
    JAX-RS 1.1 JerseyClient API – Code Sample Client client = Client.create(); WebResource resource = client.resource(“...”); //curl http://example.com/base String s = resource.get(String.class); //curl -HAccept:text/plain http://example.com/base String s = resource. accept(“text/plain”). get(String.class); http://blogs.oracle.com/enterprisetechtips/entry/consuming_restful_web_services_with
  • 52.
    JAX-RS 1.1 WADLRepresentation of Resources Machine processable description of HTTP-based Applications
  • 53.
    Generated OOTB forthe application <application xmlns=&quot;http://research.sun.com/wadl/2006/10&quot;> <doc xmlns:jersey=&quot;http://jersey.dev.java.net/&quot; jersey:generatedBy=&quot;Jersey: 1.1.4.1 11/24/2009 01:37 AM&quot;/> <resources base=&quot; http://localhost:8080/HelloWADL/resources/ &quot;> <resource path=&quot;generic&quot;> <method id=&quot;getText&quot; name=&quot; GET &quot;> <response> <representation mediaType=&quot;text/plain&quot;/> </response> </method> <method id=&quot;putText&quot; name=&quot; PUT &quot;> <request> <representation mediaType=&quot;text/plain&quot;/> </request> </method> </resource> </resources> </application>
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
    Sabyasachi Ghosh, SeniorApplication Engneer Oracle India, @neilghosh Developing RESTful Web services with JAX-RS Thank You