Upload
ngdata
View
1.729
Download
2
Tags:
Embed Size (px)
DESCRIPTION
Introduction to rest-full development with Java. Focussing on jax-rs (and kauriproject.org) Slides presented at devoxx-2010. See http://devoxx.com/display/Devoxx2K10/RESTful+development+with+Java for abstract.
Citation preview
1
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
DEVOXX LAB :: REST Development
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Lab Preparation
• You need– JDK (1.5+)– MAVEN (2.2.1)– Editor/IDE
• Download and Install (unpack)– http://kauriproject.org/files/devoxx2010/– or grab stick/CD-R passed around
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Speaker Context
Marc Portier, ±14 years of Java, XML based web development. Co-founder of Outerthought.
• Outerthought?– Innovative Content Management system that follows
ReST principles: “DaisyCMS”– New ReST supporting development framework:
“Kauri project”– Scalable Search and Store: “Lily Project”
• Outerthought is an early ReST adopter
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Looking for You!
• User, Contributor of our Open Source Projects
• Teacher, University, School
• Student• Talented worker
– Job openings!
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
The WonderfulWeb Machine
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Amazing Web
Supercalifragilisticexpialidocious !
FRANTIC COMPLEX
UNMANAGEABLECHAOTIC
Heterogenous
Layered
Decentralized
Elegant Just Works
ExtensibleSimple
Usable
Functional
Entertaining
Scalable
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
How does it keep up?
• Diversity / Compatibility
• Amount of Servers• Amount of Users• Amount of resources
• Response Times / Latency
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Core Principles & Well kept secrets
• Browsing Pages (Getting Views / Renditions)(aka Resource, URI, Representations)
• Simple and Good Enough Protocols
• Stale and Scale
• Links
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Software developers should expect that sharing
URIs across applications will be useful,
even if that utility is not initially evident.
Architecture of the World Wide Web, Volume One
http://www.w3.org/TR/2004/REC-webarch-20041215/#p39
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Request – HTTP – Response
POST /some/path?qp HTTP/1.1
Host: www.example.com:80
User-Agent: …
Accept-Language: …
Accept: …
Accept-Charset: …
Content-Type: …
X-My-Header: …
… bytes of data in entity body …
200 OK
Content-type: …
Content-Length: …
Server: …
Set-Cookie: …
Date: …
… bytes of data in http://example.com/more
entity body …
method path
request headers
empty line “\n\n”
response headers
response code
entity bodyentity body
empty line “\n\n”
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Stale And Scale
• Caching fights – Latency and network traffic.
• Critical success factor of the web.– And of your personal website!– Don't fight it for 'control' of your website.– Don't see it as a danger or problem. (hits/logs)– Design to help caches do what you think is best
• The opportunity in “stale”Allowing “stale” responses
Enhances “scalability”
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
The killer Link
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
The Killer Link
• Protocol-hypertext combination– HTML (not the first Hypertext system)– HTTP (not the first Internet protocol)
• Web of URI's was first to combine both.And went on to cannibalize the rest.– Hardly any left: gopher? ftp? wais?– Forums vs. usenet?– Version control (svn) and CMS's shifting – Even email is moving up!
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
REST
• Representational State Transfer– Historic back-thinking on the web-success.– Guidance in transition from HTTP/1.0 to HTTP/1.1
• No session layer• Instead: enhanced and clarified caching
• Roy Fielding Dissertation• An architectural style for large scale distributed
computing.• Theoretical Model, limited practice, debate-fuel
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
The “RWS” Book
• Proposes ROA • Practical and
Pragmatic• Includes “annotated
essential HTTP Reference”
• Positions RPC style
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
The Web Service Debate?Not: SOAP vs. ReST
But: RPC-style nature
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Classification of Web Services
• Q1: Method Information– How does the client convey its intentions to the
server?• HTTP method: GET, PUT, POST, DELETE• URI: e.g. GET /path?method=removeThat• Entity Body: Envelope with certain format (e.g. SOAP)
• Q2: Scope Information– How does the client tell the server which (part of the)
data to operate on• URI (path or request params)• Entity Body: Envelope with certain format (e.g. SOAP)
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Types of Web Services
• I. ReSTFull/Resource Oriented• Method info in HTTP Method.• Scoping info in URI.
• II. RPC Style• Entity Body holds Method and Scoping info.• Single URI: the 'end-point' | Single Method: POST
• III. Hybrid• Method info in the URI, next to the scope info.• Difficult to spot, only visible when not read-only.• Often grown out of classic websites.
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Pitfalls of the RPC-style
• Single endpoint: not cache-able.• Standard web-intermediaries make no sense.• Full method variation possible embedded in the
envelope: No Uniform interface. Specific clients.
• No Representations that make the client learn new paths in the application. (responses purely conform prior expectation)
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
In woodworking it's important to work with the grain
of the wood. The Web, too, has a grain, and
a RESTful web service is one that works with it.
- Leonard Richardsonand Sam Ruby
RestFull Web Services
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
REST in practice
• Understand how the web really works• How to put that into your advantage
– Reduce complexity– Enhance transparency– Leverage Linking/Connectdnesss
• Matches the fuzz– Web 2.0, RIA, mash-ups– Available libs and tools
• firebug and poster• restlet.org
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Meeting high expectations
• Current web-experiences are spoiling us– Google Maps– Mash-ups– Atom– Amazon S3
• It all looks so simple (and mostly works)• General customer feeling:
“How hard could it be?””
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
What To Expect from “REST”- APIs/LIBs/Frameworks?
• No magic
• And a lot to learn & discover
Actually, I'd be a lot happier if, as a class, these were called"HTTP Frameworks" because otherwise, there's an implication that REST is achieved by using the framework. Without implying anything about any framework, RESTlet does indeed directly map REST terminology into configuration. But in reality, a RESTful outcome is the least likely for beginners, regardless of framework. You just can't abstract away having to learn REST; once you have learned, you'll find most frameworks working against you unless their assumptions are congruous with your Own.
– Eric J. Bowman on rest-discuss(http://tech.groups.yahoo.com/group/rest-discuss/message/16824)
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
What To Expect from “REST”- APIs/LIBs/Frameworks?
• New API view on HTTP– Access to HTTP message details – Semantics mapping the REST tereminology
• Implementing more HTTP semantics– e.g. Content negotiation
• Some Guidance & Luring into new techniques– Modified instance and thread management– Supporting the #steps in typical REST design
• Using More modern Java techniques (e.g. annotations)
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Terminology
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
ROA
• Resource Oriented Architecture• Coined in the RWS Book• More practical advise and groundwork• For:
– A ReST-style architecture– For building services – Tied to the Web
• And it's main HTTP protocol
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
The Resource Oriented Architecture *
(1) Resources(2) URI's(3) Representations(4) Links Between them
The four Concepts
(1) Addressability(2) Statelessness(3) Connectedness(4) Uniform Interface
The four Properties
* as proposed by the RWS Book
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
[C1] A Resource
• Something.• Anything.
• Idea, Concept• Data record, Result, Answer, File, • Physical item, Real world object.
• As soon as it is important enough to• Reference it by itself.• Talk about it.• Get representations from it. • Perform operations on it.
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Resource Samples
• The pictures of my last trip to Mexico.• The pictures of my daughter during our last trip...• The coffee machine.• The current weather at my weather station.• The max-temperature curve over the last 14 days
• The Sales Results for this 3rd quarter
• The first blog entry for September 23rd 2008• The next five prime numbers after 1024• Some Information about ReST• A directory of resources about ReST• A map of Zwijnaarde, Ghent• The 50 most recent monetary transactions between two
account numbers
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
[C2] URI / Reference
• Universal Resource Identifier
• It is the name • And the address of a resource
• The existential property of the resource– If it doesn't have a URI, it isn't a resource– All resources have (at least) one
• http://www.w3.org/DesignIssues/Axioms (TBL)
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
URI Samples
http://pics.org/mpo/sets/2007Mexico/
http://pics.org/mpo/sets/2007Mexico/?tag=Fien
http://intranet/machines/floor4/coffee
http://home/weather/current/all
http://home/weather/hist/tempmax?start=20080909
http://intranet/sales/2008/Q3
http://myblog.com/mpo/2008/09/23/0
http://math.org/next5primes/1024
http://library.org/wiki/ReST
http://library.org/search/ReST
http://maps.org/roads/Belgium/OVL/Zwijnaarde
http://bank.com/transact/737000003679;445166488104?limit=50
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Good URI's Are...
• Descriptive– Reading the URI gives a good idea what to expect.
• No surprise / Natural• Following some pattern / structure (Hackable)
– Similar resources have similar URI's, eg• http://library.org/search/{searchterm}
• http://library.org/articlesabout/{topic}
• Long lasting associated to the resource.
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
URI to Resource Relation
• Can two resources be the same?Can two resources share the same URI?– No. Resources are the thing, the whole thing and
nothing but the thing.– URI's are UNIVERSAL
(one for the resource in the whole universe)
– Still at any given time two distinct resources might point to the same data:
• http://project.org/releases/1.0.7.tar.gz
• http://project.org/releases/latest.tar.gz
– Note: two distinct concepts!
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
URI to Resource Relation II
• Can a URI be associated to another resource?– No. The meaning should stick.– Note though: Resources do have a live-cycle. They
exist/don't-exist at any given time.
• Can one resource have more then one URI?– Yes. Alternatives make resource more accessible.
But also dilutes the value of each one.• Relates to: Are my car-keys in my normal spot(s)
– Ensure some canonical variant...
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Canonical URI's in Practice
• Advised when 2 or more URI's for one resource• Solution 1:
• All URI's return 200 OK, and representation in body• Together with special header:ContentLocation: canonical URI
• Solution 2:• Only one URI serves the content (with 200 OK)• All others return 303 See Also• Together with the header:Location: canonical URI
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
[P1] Addressability
• Question: How many URIs should you foresee?
• Answer: more!– Increase the surface area of your application.– Compare to description (email)
• Goto homepage, then query for..., take 3rd option...• Start FTP client, cd to folder, get
– Random Access Coordinates To All Resources• URI's to resources are no accidents,
but part of the design. (Else it's no resource)
• Other samples of addressable architectures:– Cells in a spreadsheet, Files on disk,– Nodes in an XML document ...
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Addressability Matters
• URIs can be published anywhere– e.g. also Email and Old media (HUMO!)
• Addresses can be talked about– Bookmark- and tagging services.– Link love!
• True Resources (with designed URIs) benefits:– Caching– Chaining & Aggregation– Translation & Validation Services– Scraping and Mash-up
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Addressability Woes
• Do I want Scraping and Mash-ups?– My Data? My Service? My Brand? My Business?– Do you really want to control all possible usage?
• Learn to see the benefits: Exposure (brand)– Without service liability.– Without bandwidth usage.– Without the building effort.
• Syndication with Encryption and Security is still an option. (If the data really is the value.)
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
[P2] Statelessness
• Every HTTP request for a resource should happen in complete isolation.– Server never relies on information from previous
messages.
• Logic Premises:– Resources are pieces of info on a server– Addressability says they all should have URI's
• Then Statelessness means all server states have a distinct URI.– e.g. page 2 from Google results about 'ReST'
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Good, Bad & Ugly Kinds of State
• The bad kind: “Conversational State”– Builds up a conversation/session.– Introduces dependency across requests.
• The good kind: “Application State”– Cleanly kept up in the client, the process, the end-
user interaction– Grown by user interaction and received links.
• The ugly kind: “Resource State”– Server side. Conform the resource life-cycle.– Why ugly (anyone?)
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Statelessness Matters
• Superlative of Addressability– The 'boemboemboem' without the 'blablabla'
(At least the 2nd time)
– Bookmark-able hooks into earlier conversations
• All benefits of addressability, Now for intermediate states:– Caching, mash-up, aggregation, translation, direct
referencing, ...
• Most importantly: positive effect on scalability– Easier distribution across load-balanced servers.
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
A matter of Control
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Who controls the state?
• Client is in charge!– Statelessness puts control at the client– The client decides on the path through the
application.
• The server serves– Humble responses to requests– Offers options (links)– Lists available next states
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
[C3] Representations
• Platonic view on things• Resource = the concept, idea, or principle• Representation = what you really get
– The data, The bytes – a COPY– Physical resources often have disappointing
representations (often status info or metadata)
• Note: representations can travel upstream.– Write operations via PUT
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Representation Variants
• Representations have specific format and language (the resource often has not)
• Clients can 'negotiate' preferred variant:• Request headers: Accept: (mimetypes)Acceptlanguage: (iso codes)
• Server can describe in which ways representations can vary:
• Response header: Vary: Accept, Acceptlanguage
• Important for caches!Vary: * //can not be cached
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Practical Content Negotiation
• 1 URI per resource is Good™• 1 URI per representation is practical
• More visible and clear• Still a canonical negotiating URI is possible• Increased “Addressability”
– Passing URI to translation and validation services
• Options• Through request parameter (@google: ?hl=nl )• In the /path/resource-name.nl.html
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
[C4] Links
• Ehrm? Not URI's?• Link = fact that the URI gets encoded in the
representation• Wow. WOW! (Let it sip through!)
• Note: soft-referencing by nature.
Imagine being 12 and getting an SMS with the number
of a new buddy to be SMS-ing with...
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
HATEOAS
• Hypertext as engine of application state(Remember: the Killer Link... and Mary Poppins)
• The 'quantum phenomena' of browser state:With each page-rendition arriving in the browser, new accessible application-states pop into existence!
• Semantics of link are important– Implicit from context / AI or end-user– Explicit through: <link@rel>, and the suggested
Link-Header (http://tools.ietf.org/html/draft-nottingham-http-link-header-10)
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
TheApplication State
Landscape
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
The App-State Landscape
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
HATEOAS Matters
• Generic (unaware) client– At run-time surprisingly 'smart' (at least helpful)
• Towards the semantic web– Links/relations annotated with semantics
• Allows for independent Progress– New URI spaces introduced
• != contradiction to “cool URI's” • Old links still serviced / redirected
– Server has to handle all, – Client stays in control
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Links – Spaces - Maps
• Public address-space is using the URI scheme• Inside the domain there are however various
kinds of 'local' scoped links– e.g. foreign-key relations– Unaware of their 'universal' notation
• i.e. potential notationS in various contexts
• Applications will need to map cross-references between entities both ways– Directing incoming request to entity– Translating local reference to (context) URI
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
[P3] Connectedness
• URI = name-addressing scheme– Then designing to use them is to ensure
Addressability
• Links = having representations hold URIs– Then designing to use them wisely is to ensure
Connectedness.
• The end-goal is to achieve some self-learning behaviour upon the clients– Publish only one entry URI
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
[P4] The uniform interface
• Limited set of resource interactions– GET, PUT, DELETE (allow for crud-like operations)– POST
• The escape for the pragmatics• The Danger zone (breaking ROA properties)
– HEAD: same as GET without the payload– OPTIONS: self-description of the resource
• Underused.• Answer in response header:Allow: GET HEAD PUT DELETE
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
And some special ones:
• The special ones– TRACE (diagnostics: loopback and route)– CONNECT (proxies acting as SSL tunnel)
• WebDAV (http://www.webdav.org/specs/rfc2518.html)
– PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, UNLOCK,
• New suggestion (from gdata: http://code.google.com/apis/gdata/docs/2.0/reference.html#PartialUpdate)– PATCH (http://tools.ietf.org/html/rfc5789)
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Properties of the uniform Interface
• The various methods are expected to work in a certain way (Reason: resilience to unreliable networks)
– GET (and HEAD) should be SAFE• No changes to server-state.• No side-effects intended by the client.• Mild side-effects accepted (log, counters, ...)
– PUT and DELETE should be IDEMPOTENT• Replay/Duplicate of the message does not change the
server-state again.
– POST, no restrictions. The Sky is the limit• Design and document for safety and idempotence! • e.g. uuid for operation, optimistic locking, ...
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
More Uniform Interfacing!
• NOT only about the request-method– Response Code! (no error-tunnelling please!)– Request Headers (e.g. content negotiation)– Response Headers
• Mainly Location, Content-Location• Don't overdo it though: stay away of subtle nuances and
unused/unknown concepts
• Essence: Principle of least surprise.– So avoid custom X-Headers and cookies
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Recap: The ROA
(1) Resources(2) URI's(3) Representations(4) Links Between them
The four Concepts
(1) Addressability(2) Statelessness(3) Connectedness(4) Uniform Interface
The four Properties
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Concepts
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Practical Design and Hacker Tips
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Resource Oriented Design
• Steps to take1. Define the data-set. 2. Split the data-set into resources.
For each resource:3. Name the resource (URI)4. Decide on the supported request methods.5. Design exchanged representations from/to clients.
1. Integrate (link) the resource with existing ones.2. Consider typical/normal flow and interaction.
6. Handle error-conditions and decide upon error-codes.
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Sample
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
URI Design Techniques
• Hierarchy and relative links• Don't overdo hierarchy (compare to OO composition)
– Changes faster then you expect!– Should be based upon intrinsic/identifying properties of the
resource– Devaluates the 'subordinate' resources
• Useful where it maps the link-spaces• Useful where it maps boundaries of functional blocks that
could be out-sourced!(linked/mashed up)
• In house conventions avoid endless discussions• e.g. common request parameters (language, chunks...)• Plural forms, ...• Typical landing pages (search/ login/ index/ ...)
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
URI Design Techniques
• Service interface versioning!• Easy as first part of path //v1/whatever
• Paths vs. request parameters• Prefer the path to 'name' resources• Request Parameters
– Have a more 'optional' ring– Are easily consistently used across URI's and Services– For arguments to algorithms
• Typical Notations• / # ? & = % have their known use• Proposed Value-list separators
– (colon) , for ordered. (e.g. {latitude},{longitude} )– (semi-colon) ; for unordered (e.g. {-listjoin|;|friends} )
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
URI-Templates
• Draft specification – http://tools.ietf.org/html/draft-gregorio-uritemplate-04
– http://code.google.com/p/uri-templates/wiki/Implementations
• Templates for generating URIs based on parameters in some 'context' (client-side)– Simple variants used in server-platforms for 'parsing'
requests as well
• Some sampleshttp://www.google.com/search?{join|&|q,num}
http://bitworking.org/news/{listjoin|/|entrypath}
http://example.com/search?q={searchTerms}&num={count}
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Matrix URIs
• Status “Personal View” (TBL, since 1996)– http://www.w3.org/DesignIssues/MatrixURIs.html
• Brings relative linking without hierarchy• Unordered attribute sets in URI paths• Sample base= //some/mapX;scale=5;roads=y
Relative links:
href=”;”//some/mapX;scale=5;roads=y
href=”;scale=2” //some/mapX;scale=2;roads=y
href=”;roads” //some/mapX;scale=5
href=”;roads=” //some/mapX;scale=5;roads=
href=”;rivers=all”//some/mapX;scale=5;roads=y;rivers=all
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Decide on Supported Request Methods
• GET (HEAD), PUT, DELETE – Obviously map the crud operations– Don't forget safety and idempotence though
• The hard job is dealing with flexible POST– When/How to use it?
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Appropriate Use of POST
• Creating subordinate resources• When Resource location is under client control:
– Request: PUT + representation– Response: 200 OK
• When Server decides on URI:– Request: POST + representation– Response: 201 Created + Location header
• Appending resource state • Avoiding full write of complete resource,e.g. add to log
• Just Pragmatics• Handle/Tunnel for Browser Client (PUT/DELETE)• PUT can't handle relative state change• Other, e.g. Batch of PUTs
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Border case Use of POST
• To be avoided: Anything that will introduce the RPC style.– Don't tunnel everything to one endpoint URI– Don't let it overtake the resource oriented design
• But pragmatics rule.– Sometimes unavoidable– Sometimes just helpful
• Operations spanning multiple resources• Incremental/Relative Updates
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Design exchanged representations
• LINKS! LINKS! LINKS!
• The adagium of Jon Postel– Be liberal in what you expect and conservative in what
you send.
• Practical trade-offs– Content negotiation is possible, sometimes
recommended, not required.– One variant will often do. (Off-line negotiation.)– Server still decides and sets Content-type header.– Representation formats are part of your service
versioning!
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Candidate formats
• Data structures– XML– json (js object notation)– Your own
• End-user Facing– HTML– PDF
• Microformats– Nice trade-off between end-user / program
Consumption
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Decide on Response Codes(http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)
• 200 “OK” - 201 “CREATED” - 202 “ACCEPTED”
• 400 “Bad Request”• Issue at client side, try harder. Check message to fix.
• 500 “Internal Server error”• Issue at server side, try later. Message informational.
• 301 “Moved Permanently”
• 404 “Not Found” - 410 “Gone”• URI can't be mapped to the resource.
• 409 “Conflict”• Request would make server-state inconsistent• e.g. foreign key relation, locking, ...
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
The Lab
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
The Lab
• [0] Java REST-Lib Listing– What is out there
• [1] Service Implementation– Practical techniques– JAXRS
• [2] Client Development (if time permits)– Transition from web-service to web-application (UI)– Demo Kauri
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
[0] Java and REST
• Servlets? (mindset: Request-Response model)• Specs and API's
– Jax-RS (jsr 311)
• Implementations @– RESTlet restlet.org
• Adds own API with annotations
– Apache CFX cfx.apache.org– Oracle/Sun Glassfish (Jersey) jersey.java.net
• Frameworks – ###
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Jax-RS
• JSR 311 https://jsr311.dev.java.net/• Clear and readable spec (±50 pages)• Helps out with common REST tasks
– URI Design and Handling• URI templates notation (@parse and @format)• Parameters in URIs
– Response Codes and Headers– Representations up- and down-stream
• Remember: no REST guarantee/enforcement• Modern & Elegant HTTP API (unlike servlets)
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
[1] ReST Service Implementation
• Exercise– Use Jax-RS (API & annotations)– Build Resty webservice for a simple blog– Limit ourselves to json Representations – No persistence / mock service
• No exceptional smart or compelling design• Only Basic ReST principles in use.• Focus: 1st experience with Jax-RS use.• Explain Jax-RS constructs as we go.
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
ResourceList & URI design
● Resource “Blog-Entry”/data/entry– GET: list of entries– POST: factory for new entry (in body) – 201!
/data/entry/{id}– GET, PUT, DELETE
• Representation (json){"title":"...","summary":"...","content":"...", "id":"2010-06-30T12:13:00", "tags": ["test"]}
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
ResourceList & URI design II
● Resource “Tags”/data/tag– GET: list of tags (cloud)– No explicit creation: implicit through entries!
/data/tag/{name}– GET: list of entries with that tag
• Representation (json){"entries":[{...}, {...}],"id":"go"}
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
JaxRS::Application
• Entry-point, deployment-unit, configuration.• Subclass javax.ws.rs.core.Application
– Configure there which classes should be loaded.
new javax.ws.rs.core.Application() {
@Override public Set<Class<?>> getClasses() { Set<Class<?>> rrcs = new HashSet<Class<?>>();
rrcs.add(MyPojoResourceClass.class);
return rrcs; }
}
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Deploy Your Application
Check docs of your deployment-platform– e.g. restlet uses a wrapper:
JaxRsApplication jaxRsApp = new JaxRsApplication(context);jaxRsApp.add(new javax.ws.rs.core.Application(){ ...});defaultHost.attach("/data", jaxRsApp);
– e.g. kauri uses groovy router & springframework DI:builder.router { jaxRs(uri: "/data", passThrough: true) { jaxRsResource(scanPackages: "*") jaxRsProvider(scanPackages: "*") jaxRsGroovyScripts(path: "groovy-jax-rs") }}
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Kauri Setup
$ cd /to/where/kauri-unpacked$ export KAURI_HOME=$(pwd)$ ls ${KAURI_HOME}/bin/*sh
• kauri-deploy-repo.sh : update mvn repo
• kauri-project-template.sh : new project
• kauri.sh : runtime
$ ${KAURI_HOME}/bin/kauri-deploy-repo.sh
$ cd ~/projects;
$ ${KAURI_HOME}/bin/kauri-project-template.sh• Type 1• ID: com.example.devoxx10:rslab:1.0-SNAPSHOT
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Jax-RS Hello-world (in Kauri)
$ cd rslab$ mvn install$ ${KAURI_HOME}/bin/kauri.sh run
• http://localhost:8888/helloworld-from-java – src/main/kauri/*.groovy– src/main/java/com/example/devoxx10/jaxrs/HelloWorldResource.java
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Jax-RS:Resources
• Any POJO + Jax-RS Annotations, mainl– @Path to trigger this resource– Request Method Designator (e.g. @GET)
• Lifecycle– Per request instance will be created– Requires Public constructor– As much as possible arguments will be passed– DI framework can be used.
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Parameters from Request context
• Applied to:– Constructor arguments– Fields & Properties – Method Arguments
• Various types:– @PathParam– @QueryParam– @MatrixParam, @CookieParam, @HeaderParam,– @Context (matches API types: Request,
Application, UriInfo, HttpHeaders,, SecurityContext, Providers, <YOUROWN>)
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
JaxRS:Resource Methods
• public• Injects annotated arguments• Returns
– Void, null >> “204” No Content– Response (from ResponseBuilder)– GenericEntity– <YOUROWN>
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
@Path(“uritemplate-{name:regex}”)
• URI-template for parsing (not generating)– Resembles a path enhanced with named
placeholders between { }– Translated into a regexp to match the request-path
• On:– Resource Class (Root-class)– Methods: declares so-called subresources that the
method will (@Path is added to the class's)• Locate (if Request-Method-Designator is absent)• Handle (if it is specified)
Exercise: Update sample to also handle hello-from-java/{name}
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Result
package com.example.devoxx10.jaxrs;
@Path("helloworld-from-java")public class HelloWorldResource {
@GET @Produces("text/html") public KauriRepresentation foo() { return foo("Hello World!"); }
@Path("{name}") @GET @Produces("text/html") public KauriRepresentation foo(@PathParam("name") String name) { Map<String, Object> data = new HashMap<String, Object>(); data.put("message", name); return new KauriRepresentation("helloworld", data); }}
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Content-Negotiation
• @Produces(mime/type) //GET@Consumes(mime/type) //POST, PUT
• Extra test in selecting the resource-method to call
• Also on @Provider that transform byte-streams into actual Java object entities– MessageBodyWriter<T>– MessageBodyReader<T>
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
@Providers
• Recurring extension mechanism for custom extensions.
• MessageBodyWriter, MessageBodyReader– Automagic entity-to-representation conversion
• ContextResolver– Request-context parameter mapping (@Context)
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
ResponseBuilder
• See API• Builder Pattern for controlling details of the
HTTP-Response• Sample:
@POST @Produces("text/plain")
public Response hello( @PathParam("world") String world ) {
final URI link = UriBuilder.fromResource( this.getClass()).build(world);
final Response resp = Response.created(link) .entity(“create at ” + link) .build(); return resp;
}
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
[2] Rest Service Consumption
• Transition from Web Service to Web App• Wiring• Client To Perforn Web-Service Calls• Client UI Elements:
– (server-side) templates and – (client-side) forms
• Demo KauriProject.org– Read data & pack into templates
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Transition from Web-Service to Web-Appliction
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Web Resources in a Web App
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Kinds Of Web Resources
• End-User Data – or 'library resources'• Content (CMS like) • Binary Downloads and 'attachments'• Full Text Search-result-lists, linking to the above• Almost directly consumed by End-Users
• “Faceless” - or 'service resources'• Manageable Data (json or XML) Items (CRUD)• Query results – Algorithm results (GET only)• Predefined one-off views/indexes (GET only)• Consumed by Custom Applications
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Kinds Of Web Resources II
• Browser-Technology-Feeds – or 'site resources'– Pages/Page Impressions
• Aggregations of data (microformat), functions and/or links (navigation, menu, help, ...)
– Styling/Skinning (CSS / Images)– Functional Applications
• Forms• JavaScript logic (or other RIA approach)
– Mashing up the data
– Consumed by web-browsers, supporting the end-user experience.
IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org
Time to take a ReST
Questions?