Restful web services with java

29
Restful Service with Java

Transcript of Restful web services with java

Page 1: Restful web services with java

Restful Service with Java

Page 2: Restful web services with java

REST● REST stands for Representational State Transfer-Design pattern for developing web services.

● Resource based● Rest Style:● Client-server● Uniform interface● Stateless● Cached● Layered system● HATEOAS - (Hypermedia As The Engine Of Application State)

Page 3: Restful web services with java

REST - not a Standard● But it uses several standards:

o HTTPo URLo XML/HTML/GIF/JPEG/etc (Resource Representations)o text/xml, text/html, image/gif, image/jpeg, etc (Resource Types, MIME Types)

Browser Web ServerGET /index.html HTTP/1.1Host: www.pitt.edu

HTTP/1.1 200 OKContent-Type: text/html

Page 4: Restful web services with java

HTTP Request• The HTTP request is sent from the client.

– Identifies the location of a resource.– Uses nouns rather than verbs to denote simple resources.– 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.)

Page 5: Restful web services with java

Sample Client Requests:GET /view?id=1 HTTP/1.1 Request HeadersUser-Agent: Chrome Accept: application/json Requested Resource (path and query

string) (no request body)

POST /save HTTP/1.1 Requested Resource (typically no query string)User-Agent: IEContent-Type: application/x-www-form-urlencoded Request

Headers

name=x&id=2 Request Body (e.g. form parameters)

Page 6: Restful web services with java

HTTP Response• 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.)– -HTTP Status codes(1xx, 2xx, 3xx, 4xx, 5xx)

Page 7: Restful web services with java

Sample Server Responses:

HTTP/1.1 200 OKContent-Type: text/htmlContent-Length: 1337[CRLF]<html> <!-- Some HTML Content. --></html>

HTTP/1.1 500 Internal Server Error

HTTP/1.1 201 CreatedLocation: /view/7[CRLF]Some message goes here.

Response Status

Response Headers

Response Body (content)

Response StatusResponse Header

Response Body

Response Status

Page 8: Restful web services with java

Standard Set of Methods ● GET - read data and not change it.● PUT - update capabilities● POST - create subordinate resources● DELETE - delete a resource● OPTIONS - ‘What methods are allowed’● HEAD - HTTP header

Page 9: Restful web services with java

A typical HTTP REST URL:

http://my.store.com/fruits/list?category=fruit&limit=20

• 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

Page 10: Restful web services with 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

Page 11: Restful web services with java

Examples of Rest URIsInsert new customer in a system

POST http://www.example.com/customers/12345

Read a customer with customer ID

GET http://www.example.com/customers/33245

Read all orders with customer ID

GET http://www.example.com/customers/33245/orders

Page 12: Restful web services with java

JAX-RS is a Java standard API for REST services:

• Services are annotation driven• Provides support for data binding.(JAX-B)• Provides advanced APIs for content negotiation.(@Produces/@Consumes)

Page 13: Restful web services with java

SOAP vs. REST: OverviewBoth SOAP and REST are front-end technologies.

SOAP – Simple Object Access Protocol Supports a variety of transports (HTTP, JMS, etc.) and integrates with a variety of web service standards. Typically used to pass contractually structured data between applications. Bound to xml. Uses SOAP envelope and then HTTP (or FTP/SMTP) to transfer the data. Slower performance and scalability is a bit complex. Caching not possible.

Page 14: Restful web services with java

REST - Representational State Transfer

Architectural style Simple point-to-point communication using well-established HTTP verbs, protocols, and standards. Supports many different data formats like JSON, XML etc. Performance and scalability, caching. Lightweight, easy to consume. Widely and frequently used.

SOAP vs. REST: Overview

Page 15: Restful web services with java

- XML-based protocol - How to access the service and what operations are performed

Broadly consists of:

- Types - Operation - Binding

WSDL- Webservices Description Language

Page 16: Restful web services with java

Connection point

Client-server response

Client-server request

WSDL Example

Name of the service

Parameter of the ws

Request-response operation

targetNamespace, default and other namespaces

Page 17: Restful web services with java

WSDL Example- contd. Define binding

transport

Endpoint URI

Connect port and binding

Page 18: Restful web services with java

Restful Webservices● A RESTful Web service follows four basic design principles:

o Uses HTTP methodso Be stateless as far as possibleo Expose directory/folder structure-like URIo Transfer XML, JSON, or both

Page 19: Restful web services with java

Java API for RESTful Web Services (JAX-RS)vs Spring MVCSome Guidelines for choosing your solution:• Both JAX-RS and Spring MVC can produce REST services.• Spring MVC is a web application framework that can be used as service framework.

– Provides better validation– Supports internationalization

• JAX-RS is a primarily a services framework.– Provides support for WADL generation– Can use CXF interceptors, filters, etc.

• Match the framework to the needs and purpose of the project.• Don’t mix both in same web application unless you need unique features from each.

– If your project needs both, consider separate web applications.

Page 20: Restful web services with java

Spring mvc architecture● Spring web MVC framework

Page 21: Restful web services with java

RESTful support in Spring

● Controllers can handle requests for all HTTP methods, including the four primary REST methods: GET, PUT, DELETE, and POST.

● The @PathVariable annotation enables controllers to handle requests for parameterized URLs (URLs that have variable input as part of their path).

● Resources can be represented in a variety of ways using Spring views and view resolvers, including View implementations for rendering model data as XML, JSON, Atom, and RSS.

The representation best suited for the client can be chosen using ContentNegotiatingViewResolver.

● View-based rendering can be bypassed altogether using the @ResponseBody annotation and various HttpMethodConverter implementations.

● Similarly, the @RequestBody annotation, along with HttpMethodConverter implementations, can convert inbound HTTP data into Java objects passed in to a controller’s handler methods.

● Spring applications can consume REST resources using RestTemplate

Page 22: Restful web services with java

Web.xml configuration

<servlet> <servlet-name>AccountService</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>app</servlet-name> <url-pattern>/*</url-pattern></servlet-mapping>

Page 23: Restful web services with java

URI Mappings example

Page 24: Restful web services with java

Content Negotiation

Page 25: Restful web services with java

Content Negotiation using views

Page 26: Restful web services with java

DEMO

Page 27: Restful web services with java

Next topics- Securing Restful Services- Open source frameworks JERSEY, RESTEASY

Page 28: Restful web services with java

References

- Restful Webservice: Leonrard Richardson and Sam Ruby//O’Reilly

- RESTful Web Services Cookbook: Subbu Allamraju//O’Reilly

- Roy Fieldings dissertation - http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm

- Spring in Action, 4th Edition, Craig Walls//Manning

Page 29: Restful web services with java

Questions