Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture IV: REST Web Service

Similar presentations


Presentation on theme: "Lecture IV: REST Web Service"— Presentation transcript:

1 Lecture IV: REST Web Service
CS 4593 Cloud-Oriented Big Data and Software Engineering

2 Outline REST Web Services Introduction to REST HTTP and REST
Use REST Services Build a REST Service 2

3 Introduction to REST REST stands for Representational State Transfer
An architectural pattern for developing web services REST web services communicate over the HTTP specification, using HTTP vocabulary: Methods (GET, POST, etc.) HTTP URI syntax (paths, parameters, etc.) Media types (xml, json, html, plain text, etc) HTTP Response codes. 3

4 Introduction to REST Representational State Transfer
Clients possess the information necessary to identify, modify, and/or delete a web resource. State All resource state information is stored on the client. Transfer Client state is passed from the client to the service through HTTP 4

5 Introduction to REST Six characteristics of REST Uniform interface
Decoupled client-server interaction Stateless Cacheable Layered Extensible through code on demand (optional) 5

6 HTTP-REST Request Basics
The HTTP request is sent from the client. Identifies the location of a resource. Specifies the verb, or HTTP method to use when accessing the resource. Supplies optional request headers (name-value pairs) that provide additional information the server may need when processing the request. Supplies an optional request body that identifies additional data to be uploaded to the server (e.g. form parameters, attachments, etc.) 6

7 HTTP-REST Request Basics
The Sample Client Requests A typical client GET request: A typical client POST request: GET /view?id=1 HTTP/1.1 User-Agent: Chrome Accept: application/json [CRLF] Requested Resource (path and query string) Request Headers (no request body) POST /save HTTP/1.1 User-Agent: IE Content-Type: application/x-www-form-urlencoded [CRLF] name=x&id=2 Requested Resource (typically no query string) Request Headers Request Body (e.g. form parameters)

8 HTTP-REST Response Basics
The HTTP response is sent from the server. Gives the status of the processed request. Supplies response headers (name-value pairs) that provide additional information about the response. Supplies an optional response body that identifies additional data to be downloaded to the client (html, xml, binary data, etc.) 8

9 HTTP-REST Response Basics
Sample Server Responses: HTTP/ OK Content-Type: text/html Content-Length: 1337 [CRLF] <html> <!-- Some HTML Content. --> </html> Response Status Response Headers Response Body (content) HTTP/ Internal Server Error Response Status HTTP/ Created Location: /view/7 [CRLF] Some message goes here. Response Status Response Header Response Body 9

10 HTTP-REST Vocabulary HTTP Methods supported by REST:
GET – Requests a resource at the request URL Should not contain a request body, as it will be discarded. May be cached locally or on the server. May produce a resource, but should not modify on it. POST – Submits information to the service for processing Should typically return the new or modified resource. 10

11 HTTP-REST Vocabulary HTTP Methods supported by REST:
PUT – Add a new resource at the request URL DELETE – Removes the resource at the request URL OPTIONS – Indicates which methods are supported HEAD – Returns meta information about the request URL 11

12 HTTP-REST Vocabulary A typical HTTP REST URL:
The protocol identifies the transport scheme that will be used to process and respond to the request. The host name identifies the server address of the resource. The path and query string can be used to identify and customize the accessed resource. protocol host name path to a resource query string 12

13 HTTP and REST A REST service framework provides a controller for routing HTTP requests to a request handler according to: The HTTP method used (e.g. GET, POST) Supplied path information (e.g /service/listItems) Query, form, and path parameters Headers, cookies, etc. 13

14 Using REST Services Simply work with ‘wget’ or any http libraries in any programming languages The return values are in XML, JSON or other specified formats

15 An Example with Google Translation API
GET The return values are in XML, JSON or other specified formats 200 OK { "data": { "translations": [ { "translatedText": "Hallo Welt" } ]

16 Building REST Services
REST services in Java web applications can be implemented in several ways: As a plain Java Servlet Adequate for very simple REST services. Requires a lot of “boiler plate” code for complex services. Using a REST service framework. Eliminates the need to write “boilerplate” code. Typically integrates with other technologies, such as Spring. 16

17 Building REST Services with Frameworks
REST Service can be implemented with simple servlet code at the server side Java provides a framework for developing REST Services JAX-RS Annotation-based framework Provides an API specification (no official implementations) 17

18 JAX-RS Basics An example REST service class:
At least one method must be annotated with an HTTP verb annotation makes the class discoverable package org.lds.tech.training.lab.ws; import javax.ws.rs.GET; import org.springframework.stereotype.Controller; @Path(“/hello”) public class HelloWebServiceRest { @GET public String sayHello() { return "Hello, World!"; }

19 JAX-RS Basics An example WADL descriptor:
<application xmlns=" xmlns:xs=" <resources base=" <resource path="/"> <method name="GET"> <response> <representation mediaType="application/octet-stream"> <param name="result" style="plain" type="xs:string"/> </representation> </response> </method> </resource> </resources> </application>

20 JAX-RS Major Implementations Jersey (from Sun) RESTlet
CXF (from Apache) RESTeasy (JBoss) WebSphere (IBM) WebLogic (Oracle) 20

21 JAX-RS Specifications @Path: the path to the resource class or method
@GET: the method invoked to response a GET request @POST: the method invoked to response a POST request @DELETE: the method invoked to response a PUT request 21

22 JAX-RS @Path Annotation
@Path annotations may be supplied to customize the request URI of resource. @Path on a class defines the base relative path for all resources supplied by that class. @Path on a Java class method defines the relative path for the resource bound to that method.

23 JAX-RS @Path Annotation
@Path on a method is relative to on the class. In the absence on the class or method, the resource is defined to reside at the root of the service. A leading forward slash (/) is not necessary as the path is always relative.

24 JAX-RS @Path Annotation
@Path annotation supports the use of template parameters in the form: { name : regex } @Path("/users/{username}") public class UserResource { @GET @Produces("text/xml") public String String userName) { ... }

25 JAX-RS @Path Annotation
The template parameter name is required. The colon (:) followed by a regular expression is optional and will default to the pattern: [^/]+ Multiple template parameters may be defined in a Template parameter values will be injected into method parameters annotated @Path("users/{username: [a-zA-Z][a-zA-Z_0-9]}")

26 JAX-RS @Path Annotation
An code sample with multiple templates @Path("/") public class CustomerResource { @GET @Path("customers/{firstname}-{lastname}") public String String first, @PathParam("lastname") String last) { ... }

27 JAX-RS @Path Annotation
Precedence Rules If the URI is “/customers/bill-gates/address”? 1 /customers/{id}-{name}/address 2 /customers/{id : .+}/address 3 /customers/{id}/address 4 /customers/{id : .+}

28 JAX-RS @Path Annotation
Rules: The number of literal characters contained within the expression, sorted in descending order. The number of template expressions within the expression, sorted in descending order. Finally, the number of regular expressions contained within the expression, sorted in descending order.

29 JAX-RS @Path Annotation
Precedence Rules If the URI is “/customers/bill-gates/address” 1 > 2,3 > 4 1>2,3 2>3 1 /customers/{id}-{name}/address 2 /customers/{id : .+}/address 3 /customers/{id}/address 4 /customers/{id : .+}

30 JAX-RS Specifications @*Param: bind method parameters to URI parts
@PathParam: bind method parameters to path @QueryParam: bind method parameters to query parameters @FormParam: bind method parameters to request header 30

31 JAX-RS Parameter Annotations
Most often used on service methods to annotate input parameters. Additional parameter annotations are also available

32 JAX-RS Annotations: Examples
@Path("example") public class ExampleWebServiceRest { @GET public Item Long id) { example } @POST public Response Long id, @FormParam("value") String value) { example @Path("{category}/{subcategory:[^/]*}") public List<Item> getItems( @PathParam("category") String category) { @PathParam("subcategory") String subcategory) { example Notes: The getItem and editItem methods are both bound to the same URI path, but the first uses GET and the second POST value maps to a matched path segement from annotation. annotation value can uses the {} notation to identify a path segment. Regular expressions can also be used with care inside the {} of annotation {name:regex} for matching path parameters. Note the subcategory pattern overrides the default by allowing the subcategory to be empty. This can be a useful trick to return all items for the category. 32

33 JAX-RS Specifications @Produces: the format of the response body
@Consumes: the format of the query body for PUT request Types: Same with HTTP content types text/plain, text/html, video/avi, application/xml, application/json, image/jpeg, … 33

34 JAX-RS Annotations: @Produces
Used on a class or method to identify the content types that can be produced by that resource class or method. Method annotation overrides class annotation If not specified, JAX-RS assumes any type (*/*) can be produced.

35 JAX-RS Annotations: @Consumes
Used on a class or method to identify the content types that can be accepted by that resource class or method. Method annotation overrides class annotation If not specified, JAX-RS assumes any type (*/*) is acceptable. JAX-RS responds with HTTP status “406 Not Acceptable” if no appropriate method is found.

36 JAX-RS Annotations Examples of @Produces and @Consumes:
The client submits JSON or XML content with the “Content-Type” header. The client requests either JSON or XML content through use of the HTTP “Accept” request header. @Path("example") public class ExampleRestService { @POST @Path("items") @Produces({"application/json", "application/xml"}) @Consumes({"application/json", "application/xml"}) public List<Item> editItems(List<Item> items) { // Does something and returns the modified list } Notes: value maps to a matched path segement from annotation. annotation value can uses the {} notation to identify a path segment. Regular expressions can also be used with care inside the {} of annotation {:regex} for matching path parameters. 36

37 JAX-RS: XML and JSON Providers
JAX-RS requires support for reading and writing XML to and from JAXB annotated classes. JAX-RS also requires built-in support for reading and writing JSON to and from JAXB annotated classes. Default support uses Jettison as the JSON provider The Stack RS namespace handler will automatically configure Jackson as the JSON provider if it is on the classpath.

38 JAX-RS: XML and JSON Providers
Choosing output formats passing a query parameter like format specify it using extensions(changing /users url to /users.json to get the users in json format) specifying the requested format(xml, json, xls, ...) by setting Accept http header.

39 Demo Demo on generating a web service with RESTLet

40 JAX-RS: Customizing the Response
There may be cases when you need to customize the response from your JAX-RS service: To provide metadata instead of, or in addition to, the response entity. To supply a custom status code To instruct JAX-RS to perform a redirect For these cases, JAX-RS provides the abstract Response class and the ResponseBuilder utility An example is provided on the following screen

41 JAX-RS: Customizing the Response
@Path("example") @Produces({"application/json", "application/xml"}) @Consumes({"application/json", "application/xml"}) public class ExampleRestService { @GET public List<Item> getItems() { // Return all items. return items; } @POST @Path("items") public Response editItems(List<Item> items) { // ... Modify the list of items ResponseBuilder rb = Response.temporaryRedirect( URI.create(UriInfo.getBaseUri() + "example")); return rb.build(); // redirect to getItems() 41

42 JAX-RS: Exception Handling
By default, JAX-RS provides exception handling for its own javax.ws.rs.WebApplicationException. Extends java.lang.RuntimeException May be thrown by any resource method Is converted by into a Response object. Any other exception will result in HTTP status “500 Internal Server Error”

43 JAX-RS: Exception Handling
There may Custom exception handling can be provided by doing the following: Implement javax.ws.rs.ext.ExceptionMapper for the exception type you want to handle. Annotate the implementation class Configure an instance of your provider as a Spring bean.

44 JAX-RS: Custom Exception Mapper
@Provider public class TimeoutExceptionMapper implements ExceptionMapper<TimeoutException> { public Response toResponse(TimeoutException exception) { ResponseBuilder rb = Response.status(408); // Request timeout // Call additional methods on the response builder // to further customize the response return rb.build(); } In this example, we have stubbed out the implementation of an ExceptionMapper that takes a TimeoutException and responds with HTTP status “408 Request Timeout” annotation is required by JAX-RS. The toResponse method obtains a ResponseBuilder from one of the factory methods on the Response class, then builds and returns the Response object. 44

45 Summary How to build a web service JAX-RS
Implementations: CXF, RESTLet, Jersey, … Annotations: PATH, POST, GET, … I/O Handling Exception Handling

46 Next Class How to build a web service on a cloud Google App Engine
Quota and Pricing Deploy web service on Google App Engine Post of the course project


Download ppt "Lecture IV: REST Web Service"

Similar presentations


Ads by Google