Rest – representational state transfer
Upcoming SlideShare
Loading in...5

Like this? Share it with your network


Rest – representational state transfer

Uploaded on


More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads


Total Views
On Slideshare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


  • 2. Agenda●Prerequisites○URI/URL○HTTP●What is REST?●REST based services●Java based implementations○JAX-WS (JSR 311)
  • 3. Prerequisites
  • 4. URI/URL●URI – Uniform Resource Identifier●URL – Uniform Resource Locator●Location or address of the resource on theweb●Uniform approach to represent a resource[scheme:][//authority][path][?query][#fragment]●Resource○ shakira●Representation○ XML, HTML, RSS, JSON, ATOM …
  • 5. HTTP – Hyper Text TransferProtocol●RFC -●HTTP is a stateless protocol●HTTP methods (in order of popularity):‣ GET, POST‣ PUT, DELETE‣ HEAD, OPTIONS, TRACE
  • 6. HTTP Methods vs. VERBSHTTPMethodCRUDActionDescription Status CodesPOST CREATECreate a resource andother operations, as ithas no definedsemantics201, 400, 422GET RETRIEVERetrieve arepresentation of aresource200, 301, 410PUT UPDATECreate or update aresource200, 301, 400, 410DELETE DELETE Delete a resource 200, 204
  • 7. Standardized HTTP ResponseCodesHTTP Status Code Meaning1xx Informational2xxSuccess3xxRedirection4xxClient Error5xxServer Error200 - OK 301 - Moved Permanently 400 - Bad Request201 - Created 410 - Gone204 - No Content 422 - Unprocessable Entity
  • 8. GET●GET ExampleHTTP/1.1 200 OKDate: …Server:...Content-Length: 1456Content-Type:application/html<html></html>GET /artists/shakiraHost: sonybmg.comAccept:application/xml
  • 9. POST●POST ExampleHTTP/1.1 201 CreatedDate: …Content-Length: 0Location: /artists/Host:<html>…</html>
  • 10. PUT●PUT ExampleHTTP/1.1 201 CreatedDate: …Content-Length: 0PUT /artists/shakiraHost:<html></html>
  • 11. DELETE●DELETE ExampleHTTP/1.1 204 No ContentDate: …Content-Length: 0DELETE/artists/shakiraHost:<html></html>
  • 12. HTTP Architectural Strength●Replication of stateless content is low-cost& easy.●The GET and HEAD methods SHOULDNOT have the significance of taking anyaction, other than retrieval.●We can cache the GET responses●The HTTP GET, PUT and DELETEmethods are idempotent, but the POSTmethod creates new resources
  • 13. REST - “RepresentationalState Transfer”
  • 14. REST - “Representational StateTransfer”●“REST” was introduced in 2000 in thedoctoral dissertation of Roy Fielding●Imposes some architectural constraintsthat are applicable to the architecture of adistributed system●Architectural style of the web & not astandard
  • 15. REST Principles●Application state and functionality areabstracted into resources●Every resource is uniquely addressableusing a universal syntax used inhypermedia links. Resource is anaddressable spaceCourtesy:
  • 16. REST Principles cont…●All resources share a uniform interface forthe transfer of state between client andresource, consisting of○A constrained set of well-defined operations○A constrained set of content types, optionallysupporting code on demand●A protocol which is:○Client-server○Stateless○Cacheable○Layered
  • 17. Designing a RESTful application●Identify resources●Design URIs (URLs)●Content Negotiation●Identify method semantics●Select response codesCourtesy:
  • 18. Designing a RESTful application●Identify resources - Artists●Design URL’s●Content Negotiation○What type of content will be used to passinformation from client to server○What type of content will be passed back tothe client●Identify method semantics (GET, POST,…)○Resources methods are mapped to HTTP
  • 19. Domain Example●Artist information systemArtistInformationService+getArtistsList()+getArtistInfoByName(String name)+addArtistInfo(Artist)+updateArtistInfo(Artist)+deleteArtistInfo(id)
  • 20. ●+getArtistsList()○ GET●+getArtistInfoByName(String name)○ GET●+addArtistInfo(Artist)○ POST form data to●+updateArtistInfo(Artist)○ POST form data to●+deleteArtistInfo(id)○ POST Approach
  • 21. ●+getArtistsList()○ GET●+getArtistInfoByName(String name)○ GET●+addArtistInfo(Artist)○ POST the artist data to●+updateArtistInfo(Artist)○ PUT the artist data at●+deleteArtistInfo(id)○ DELETE Approach
  • 22. JSR 311:JAX-RS: The Java™ APIfor Restful Web Services
  • 23. JAX-RS: JSR-311●Java™ API for RESTful Web Services●POJO as a Web resources●HTTP-centric●Format & Container independent●Can be hosted in a Java EE container
  • 24. JSR-311 Approach●One class per resource “type”●Methods to handle HTTP requests●Use of Java 5 Annotations to specify○URI Mapping (@Path, @Encoded)○Mapping to HTTP methods(@GET, @POST,@PUT,@DELETE, @HEAD or @HttpMethod )○Mapping of URI components(@QueryParam,@PathParam, @CookieParam, @FormParam,@MatrixParam, @DefaultValue)○HTTP headers(@HeaderParam)○HTTP entities to method parameters and returntypes○MIME type information(@Produces, @Consumes)
  • 25. Main packages●○ High-level interfaces and annotations used to createRESTful service resources.●○ Low-level interfaces and annotations used to createRESTful service resources.●○ APIs that provide extensions to the types supported by theJAX-RS API.
  • 26. Example@Path("/cps/artists/{name}")public class ArtistResource {private ArtstService artistService = …;@GET @Produces(MediaType.APPLICATION_XML)public String getArtistByNameAsXML(@PathParam("name") String artistName) {return artistService.getArtistAsXML(artistName) ;}@GET @Produces(MediaType.APPLICATION_XHTML_XML)public String getArtistByNameAsXHML(@PathParam("name") String artistName) {return artistService.getArtistAsXHML(artistName) ;}@GET @Path("#{albumName}")@Produces(MediaType.APPLICATION_XML)public String getArtistAlbumAsXML(@PathParam("name") String artistName, @PathParam("albumName") StringartistAlbumName) {return artistService.getArtistAlbumAsXML(artistName, artistAlbumName) ;}@POST @Consumes(MediaType. APPLICATION_XML)public String createArtist(String artistXml) {try { artistService.createArtist(artistXml);return Response.ok().build();} catch (Exception e) {e.printStackTrace();return Response.status(400).entity("Please send well-formed XMLn").type("text/plain").build();}}}
  • 27. URI Template●URI Templates define URI strings withembedded variables(are denoted by curlybraces).●The URI template{name}Maps to Shakira URL from previousexample
  • 28. @Path●The @Path can be annotated on a classor on a method.●@Path annotation on a class○Maps class to a URI space, relative to a baseURI○Base URI will beresolved to●@Path annotation on a method○Maps method relative to the class URI○URI will beresolved to
  • 29. @Path●Template Parameters can be validatedusing regular expressionsE.g. @Path(“/artists/{name: [a-zA-Z][a-zA-Z_0-9]}")Note: Failure of validation causes a 404 asthe request cannot be mapped to a resource
  • 30. @Path●An @Path value may or may not, begin orend with a forward slash (/).●The request URLs that end or do not endwith a forward slash will both be matched.●Jersey has a redirection mechanism,which, if enabled, automatically performsredirection to a request URL ending in a /if a request URL does not end in a / andthe matching @Path does end in a /.
  • 31. @PathParam●Binds the value of a URI templateparameter or a path segment containingthe template parameter to○a resource method parameter○a resource class field○a resource class bean property.●A class annotated with: @Path(“artists/{name}") can have methods annotatedwhose arguments are annotatedwith @PathParam(“name").
  • 32. @QueryParam●Binds the value(s) of a HTTP queryparameter to a resource method parameter,resource class field, or resource class beanproperty.@GET@Produces(MediaType.APPLICATION_XML)public String getAllArtists (@QueryParam(“fromIdx”) long fromIdx,@DefaultValue(“1000”)@QueryParam(“totalCount”) longtotalCount) {
  • 33. Restrictions of QueryParam &PathParam●@QueryParam and @PathParam can only beused on the following Java types:○All primitive types except char○All wrapper classes of primitive types exceptCharacter○Have a constructor that accepts a single Stringargument○Any class with the static method named valueOf(String) that accepts a single String argument○Any class with a constructor that takes a single Stringas a parameter○List<T>, Set<T>, or SortedSet<T>, where T matchesthe already listed criteria. Sometimes parameters maycontain more than one value for the same name. Ifthis is the case, these types may be used to obtain all
  • 34. @FormParam, @CookieParam &@HeaderParam●@FormParam – This annotation is used toextract parameters from a formsubmission. It is used in conjunction withHTTP POST method.●@CookieParam – CookieParam is used toextract values form a cookie.●@HeaderParam – This annotation is usedto extract parameters from HTTP header
  • 35. @MatrixParam●@MatrixParam - This annotation is usedto extract parameters from matrix URI.Note:● By default QueryParam, PathParam, FormParam or MatrixParamvalues will be decoded. e.g., Bryan%20Adams will be converted toBryan Adams.● If you want to disable this automatic decoding of parameter valuesuse annotation in conjunction to QueryParam,PathParam, FormParam or MatrixParam annotations● Using this annotation on a method will disable decoding for allparameters. Using this annotation on a class will disable decodingfor all parameters of all methods.
  • 36. Request Method DesignatorAnnotations●@HEAD - Indicates that the annotated methodresponds to HTTP HEAD requests●@GET - Indicates that the annotated methodresponds to HTTP GET requests●@PUT - Indicates that the annotated methodresponds to HTTP PUT requests●@DELETE - Indicates that the annotatedmethod responds to HTTP DELETE requests●@POST - Indicates that the annotated methodresponds to HTTP POST requestsNote:● The @HttpMethod(“GET”) and @GET or synonymous.● See for HTTP status code
  • 37. Configuring the Resource with theRuntime●web.xml<servlet><servlet-name>Jersey Web Application</servlet-name><servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class><init-param><param-name></param-name><param-value>com.sonybmg.cps.resources</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>Jersey Web Application</servlet-name><url-pattern>/*</url-pattern></servlet-mapping>
  • 38. Exception Handling●JAX-RS has a RuntimeException class,WebApplicationException, that allows youto abort your JAX-RS service method.●It can take an HTTP status code or even aResponse object as one of its constructorparameters.
  • 39. Exception Handling@POST @Consumes(MediaType. APPLICATION_XML)public String createArtist(String artistXml) {try {artistService.createArtist(artistXml);return Response.ok().build();} catch (XMLFormatException e) {logger.error(“Invalid XML {}”, e);ResponseBuilder builder = Response.status(Status.NOT_FOUND);builder.type("text/html");builder.entity("<h3>"Please send well-formed XMLn"</h3>");throw new WebApplicationException(;throw new WebApplicationException(Response.status(400).entity("Please send well-formed XMLn").type("text/plain").build());return Response.status(400).entity("Please send well-formed XMLn").type("text/plain").build();}}
  • 40. Other Frameworks●Restlet●JBoss RESTEasy●Apache CXF●Jersey
  • 41. Tools of Trade●Below are the tools that to test RESTapplications.●Mozilla Plug-in