Upload
erin-taylor
View
229
Download
5
Tags:
Embed Size (px)
Citation preview
RESTful Web Services
Web Services Classification
• “Big Web Services”• Traditional enterprise Web services
• SOAP & WSDL
• “Lighter-weight Web Services”• RESTful approach
• Web API (feature of Web 2.0)
• Mashups
RESTful
• REST (REpresentational State Transfer)
is an architectural style for accessing information on the Web
• The term REST was introduced
and defined in 2000 by
Roy Fielding in his
doctoral dissertation
Another definition
• Definition from:http://java.sun.com/developer/technicalArticles/WebServices/restful/
REST is a key design idiom that embraces a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URLs
Key REST principles
• REST is a set of principles that define how Web standards, such as HTTP and URIs, are supposed to be used• Give every “thing” an ID• Link things together• Use standard methods (GET, POST,…)• Resources with multiple representations• Communicate statelessly
[1] Give every “thing” an ID
• On the Web, there is a unified concept for IDs:
The URI
• URIs make up a global namespace, and using URIs to identify your key resources means they get a unique, global ID
http://example.com/customers/1234http://example.com/orders/2007/10/776654http://example.com/products/4554http://example.com/processes/salary-increase-234
[1] Give every “thing” an ID
• Use URIs to identify everything that merits being identifiable
• All of the “high-level” resources that your application provides, whether they represent • individual items• collections of items• virtual and physical objects• computation results
Set of URIs for bookmarking system
• http://example.com/app/users/
List all users
• http://example.com/app/users/userA
Provides specific user details
• http://example.com/app/users/userA/bookmarks
List all user bookmarks
• http://example.com/app/users/userA/bookmarks/b1
Provides specific user bookmark details
[2] Link things together
<order self='http://example.com/customers/1234' > <amount>23</amount> <product ref='http://example.com/products/4554' /> <customer ref='http://example.com/customers/1234' /> </order>
• Sample Web service response:
• Links are provided, so an application that has retrieved this document can “follow” the links to retrieve more information
[3] Use standard methods
• RESTful web services use HTTP protocol methods for the operations they perform
Source: http://www.javapassion.com/webservices/RESTPrimer.pdf
[4] Multiple representations
• Client and Web service may exchange data in a variety of formats, e.g.• XML
• JSON
• YAML
• To understand each other a content negotiation procedure may be applied• Web service may provide multiple representations of
resources
• A client may ask for a representation in a particular format
Content negotiation
• Client set an ‘Accept’ header:
• URI-based:
GET /fooAccept: application/json
GET /customers/1234 HTTP/1.1Host: example.com Accept: text/x-vcard
GET /customers/1234 HTTP/1.1Host: example.com Accept: application/vnd.mycompany.customer+xml
GET /foo.json
HTTP Request/Response as REST
Source: http://www.javapassion.com/webservices/RESTPrimer.pdf
JSON
• JSON (JavaScript Object Notation) is a lightweight computer data interchange format
• Text-based, human-readable format for representing simple data structures and associative arrays• easy for humans to read and write
• easy for machines to parse and generate
• Is based on a subset of the JavaScript programming language
• MIME type: application/json
JSON example{ "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ], "newSubscription": false, "companyName": null }
JSON Web page: http://json.org/
YAML
• YAML is yet another human-readable data serialization format (first proposed in 2001)
• Takes concepts from programming languages such as C, Perl, and Python, and ideas from XML
• YAML is a recursive acronym for
"YAML Ain't Markup Language“
(data-oriented, rather than document markup)• Early in its development:
"Yet Another Markup Language"
YAML example
---receipt: Oz-Ware Purchase Invoicedate: 2007-08-06customer: given: Dorothy family: Gale
items: - part_no: A4786 descrip: Water Bucket (Filled) price: 1.47 quantity: 4
- part_no: E1628 descrip: High Heeled "Ruby" Slippers price: 100.27 quantity: 1...
JSON versus YAML
• JSON syntax is a subset of YAML 1.2
• Most JSON documents can be parsed by a YAML parser
• JSON's semantic structure is equivalent to the optional "inline-style" of writing YAML
• The Official YAML Web Site:http://www.yaml.org/
What Makes Up a RESTful Service?
The definition of RESTful web service consists of
1. The base URI for the web service • e.g. http://example.com/resources/
2. The MIME type of the data supported by the web service • e.g. JSON, XML, YAML
3. The set of operations supported by the web service using HTTP methods • e.g. POST, GET, PUT, DELETE
JAX-WS for RESTful Web Services
• The Java API for XML Web Services (JAX-WS) provides full support for building and deploying RESTful Web services
• Sun article about programming RESTful Web Services with JAX-WS: http://java.sun.com/developer/technicalArticles/WebServices/restful/
• But there is another specification JAX-RS• Java API for RESTful Web Services
JAX-RS
• JSR 311: http://jcp.org/en/jsr/detail?id=311
• Part of the Java EE 6 platform, JAX-RS fully supports REST principles
• Uses annotations to simplify the development of RESTful web services
• Allow you to expose simple POJOs as web resources
Jersey
• Sun offers the open source, production quality
Reference Implementation for JAX-RS
code-named Jersey
• Jersey also provides an API so that developers may extend Jersey to suite their needs
The Resource Class
• JAX-RS resource is any POJO that is annotated with @Path with relative URI path as value• The base URI is the application context
import javax.ws.rs.Path;
@Path("/stockquote")public class StockResource { ....... ...... public String getStockInfo() { return "This is Stock Information"; }}
Resource Methods
• Resource methods are public methods of a resource class that you identify with a request method designator• @GET, @PUT, @POST, @DELETE • @HEAD, @OPTIONS
• The return values of methods with request designator annotations are generally • void
• a Java language type• javax.ws.rs.core.Response
Example ( http://www.javapassion.com/webservices/jaxrs.pdf )
// Assume the application context is // http://example.com/catalogue, then//// GET http://example.com/catalogue/widgets // - handled by the getList method// GET http://example.com/catalogue/widgets/nnn // - handled by the getWidget method.
@Path("widgets")public class WidgetsResource {
@GETString getList() {...}
@GET @Path("{id}")String getWidget(@PathParam("id") String id) {...}
URI Path Template
• URI path templates are URIs with variables embedded within the URI syntax
• The value of the bookmark variable may be obtained by adding the @PathParam on method parameter
// Will respond to http://example.com/bookmarks/1234@Path("/bookmarks/{bookmark}")public class BookmarkResource {
@GETpublic String getBookmark(
@PathParam("bookmark") String bookmarkId) {...}
Resource method parameters
• Resource methods can be annotated with one of the following annotations:
http://www.devx.com/Java/Article/42873/0/page/2
Sub Resources
• Apart from the resource class, it is possible also to annotate methods of a resource class with the @Path annotation (sub resource methods)
@Path("/sayHello")public class SayHello {
public SayHello() { }
@GET @Path("lastname") public String hello() { .............. }}
GET request from the URI /sayHello/lastname will be handled by the hello() sub-resource method in the SayHello resource class
MIME Types Specification
• A resource class can produce or consume any type of MIME
• Use @Produces to specify the MIME type for the response • a representation that can be produced by a resource
and sent back to the client
• Use @Consumes to specify the MIME type for the request • a representation of the specific content types that a
resource can accept from an HTTP request entity
Example: MIME specification
@Path("/sayHello")
@Produces("application/xml")
public class SayHelloResource {
@GET
public String getXml() {...}
@GET
@Produces("text/html")
public String getHtml() {...}
@PUT
@Consumes("application/xml")
public void putXml(String content) {...}
}
WADL
• The Web Application Description Language (WADL) is an XML-based file format that provides a machine-readable description of RESTful Web services
• REST equivalent of WSDL version 1.1
• WSDL 2.0 can be used to describe REST Web services, thus competing with WADL
WADL sample
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://research.sun.com/wadl/2006/10">
<doc xmlns:jersey="http://jersey.dev.java.net/"
jersey:generatedBy=
"Jersey: 0.10-ea-SNAPSHOT 08/27/2008 08:24 PM"/>
<resources base="http://localhost:9998/">
<resource path="/helloworld">
<method name="GET" id="getClichedMessage">
<response>
<representation mediaType="text/plain"/>
</response>
</method>
</resource>
</resources>
</application>
WADL generation
• Jersey generates basic WADL at runtime out of the box• http://path.to.your/restapp/application.wadl
• Additionally, you can configure Jersey to create an extended WADL to add more information to the generated WADL
• Additionally, there's the maven-wadl-plugin that allows you to create the WADL without running your REST application
Deployment as Web application
• JAX-RS applications are packaged in WAR file and deployed on a container that supports Servlets
• For JAX-RS aware containers (e.g. Jersey uses a HTTP web server called Grizzly)
• web.xml can point to Application subclass
• For non-JAX-RS aware containers• web.xml points to the servlet implementation of
JAX-RS runtime
Jersey Web app configuration<?xml version="1.0" encoding="UTF-8"?>
<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>com.sun.jersey.config.property.packages</param-name>
<param-value>com.sun.jersey.samples.helloworld.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>
</web-app>
JavaSE 6 Deployment
• Use RuntimeDelegate to create instance of RESTful Web service end point
• Jersey supports Grizzly, light-weight HTTP server and JAX-WS provider
Application app = new MyRESTApplication();RuntimeDelegate rd = RuntimeDelegate.getInstance();Adapter a = rd.createEndpoint(app, Adapter.class);SelectorThread st = GrizzlyServerFactory.create(
“http://127.0.0.1:8084/”, a);
Jersey Sample Projects
• Jersey provides a package with ~ 25-30 sample projects• Description:
http://wikis.sun.com/display/Jersey/Main
• Download:
http://download.java.net/maven/2/com/sun/jersey/samples/jersey-samples/
• To run some sample projects Glassfish application server is necessary• https://glassfish.dev.java.net/
Poster: Firefox Add-on
• A developer tool for
interacting with web services and other web resources
that lets you
make HTTP requests,
set the entity body, and content type.
This allows you to interact with web services and inspect the results...
https://addons.mozilla.org/en-US/firefox/addon/2691
Poster: Firefox Add-on
Web API
• Web APIs are functionalities made available by websites to their users or visitors in a programmatically way
• Developers can use these Web APIs and enrich their applications with useful functions from third parties
• Web API is a new direction to follow by W3C in a new working group: Web APIs Working Group
http://www.w3.org/2006/webapi/
Web API
• Some of the most well-known web APIs are • Google Maps or Google Search• Yahoo Maps or Yahoo Search• eBay API• Amazon API• Paypal API• Skype API• and many more
• Some links:• http://www.programmableweb.com/apis • http://www.webapi.org • http://www.w3.org/2006/webapi/
Public REST APIs
• arXiv API - Academic research repositoryhttp://www.programmableweb.com/api/arxiv
Mashups
• Mashup is a web page or application that combines data or functionality from two or more external sources to create a new service
• Easy, fast integration, frequently using open APIs and data sources
• Types of mashups:• consumer mashups
• data mashups
• enterprise mashup
References
• Web Services Programming (with Passion!) Hands-on Online Coursehttp://www.javapassion.com/webservices/
• Article: A Brief Introduction to REST
http://www.infoq.com/articles/rest-introduction
• Article: JAX-RS: Developing RESTful Web Services in Java
http://www.devx.com/Java/Article/42873/
References
• JAX-RS specificationhttp://jcp.org/en/jsr/detail?id=311
• JAX-RS Jerseyhttps://jersey.dev.java.net/
• Common REST Mistakeshttp://www.prescod.net/rest/mistakes/
References
• Services Mashups: The New Generation of Web Applicationshttp://dsonline.computer.org/portal/site/dsonline/menuitem.9ed3d9924aeb0dcd82ccc6716bbe36ec/index.jsp?&pName=dso_level1&path=dsonline/
2008/09&file=w5gei.xml&xsl=article.xsl