You are on page 1of 34

XML and Web Technologies

Lecture 14: RESTful Services


http://acet.rdg.ac.uk/~mab/Education/Undergraduate/CS2K7/Lectures/

Prof Mark Baker


ACET, University of Reading Tel: +44 118 378 8615 E-mail: Mark.Baker@computer.org Web: http://acet.rdg.ac.uk/~mab
Spring 2010 mark.baker@computer.org

Understanding REST
What is REST?
REST is an architectural style for distributed systems. An architectural style is:
a coordinated set of architectural constraints that restricts the roles/features of elements and the allowed relationships among those elements within any architecture that conforms to that style.

or
an abstraction, a design pattern, a way of discussing an architecture without concern for its implementation.

Spring 2010

mark.baker@computer.org

Understanding REST
What is REST?
REST defines a series of constraints for distributed systems that together achieve the properties of:
Simplicity, Scalability, modifiable, performance, visibility (to monitoring), portability and reliability.

A system that exhibits all defined constraints is RESTful! Systems may add additional constraints or relax existing constraints, in which case they are more or less RESTful:
REST is not a set of laws or even a specification it is a style
Spring 2010 mark.baker@computer.org

Understanding REST
Representational State Transfer:
The Resource:
A resource is any information that can be named: documents, images, services, people, an collections.

Resources have state:


State may change over time.

Resources have identifiers:


A resource is anything important enough to be referenced.

Resources expose a uniform interface:


System architecture simplified, visibility improved, Encourages independent evolution of implementations.

Spring 2010

mark.baker@computer.org

Understanding REST
Representational State Transfer:
On request, a resource may transfer a representation of its state to a client:
Necessitates a client-server architecture.

A client may transfer a proposed representation to a resource:


Manipulation of resources through representations.

Representations returned from the server should link to additional application state:
Clients may follow a proposed link and assume a new state Hypermedia as the engine of application state.

Spring 2010

mark.baker@computer.org

Understanding REST
Representational State Transfer:
Stateless interactions:
Each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server.

Statelessness necessitates self-descriptive messages:


Standard media types, Meta-data and control-data.

Uniform interface + Stateless + Self-descriptive = Cacheable:


Cacheable necessitates a layered-system.

Spring 2010

mark.baker@computer.org

Understanding REST
What is REST:
REST is a coordinated set of architectural constraints that attempts to minimise latency and network communication while at the same time maximizing the independence and scalability of component implementations. . REST enables the caching and reuse of interactions, dynamic substitutability of components, and processing of actions by intermediaries, thereby meeting the needs of an Internet-scale distributed hypermedia system (Roy Fielding), Principal author of the HTTP 1.0, HTTP 1.1, and URI spec. Co-founder of The Apache Software Foundation.
Spring 2010 mark.baker@computer.org

Using HTTP to build REST Applications


What distributed systems protocol supports the implementation of REST applications?

HTTP 1.1
URIs: RFC 3986
Spring 2010 mark.baker@computer.org

aka RFC 2616

Media Types (multiple RFCs, IANA)

MIME: RFCs 2045/2046

Using HTTP to build REST Applications


What HTTP is:
Purposefully designed, REST conformant, Frequently abused, Wildly successful, An application protocol.

Spring 2010

mark.baker@computer.org

Using HTTP to build REST Applications


HTTP: A brief introduction:
A stateless, client/server, request/response application protocol, Clients make requests of servers using four main operations (uniform interface):
GET, POST, PUT, DELETE (there are others),

A request is sent to a specified URI (addressabilty), An HTTP request/response is an envelope, Inside the envelope are headers followed by a resource representationif any (self-descriptive).

Spring 2010

mark.baker@computer.org

Using HTTP to build REST Applications


The REST Recipe:
Find all the nouns, Define the formats, Pick the operations, Highlight exceptional status codes.

Spring 2010

mark.baker@computer.org

Using HTTP to build REST Applications


Find all the nouns:
Everything in a RESTful system is a resource a noun. Every resource has a URI, URIs should be descriptive: http://example.com/expenses;pending Not a REST principle, but a good idea! URIs should be opaque:
automated (non-human) clients should not infer meaning from a URI.

Spring 2010

mark.baker@computer.org

Using HTTP to build REST Applications


Find all the nouns:
Use path variables to encode hierarchy: /expenses/123 Use other punctuation to avoid implying hierarchy: /expenses/Q107;Q307 /expenses/lacey,peter Use query variables to imply inputs into an algorithm: /search?approved=false Caches tend to (wrongly) ignore URIs with query variables! URI space is infinite (but URI length is not ~ 4K).

Spring 2010

mark.baker@computer.org

Using HTTP to build REST Applications


Resource Bill's expense reports Expense report #123 All expense reports (you're allowed to see) All pending (new, etc.) expense reports Bill's pending expense reports Expense 123s line items Line item 2 of Expense 123 2006 expenses 2006 open expenses URI /users/bill/expenses /users/bill/expenses/123 /expenses/ /expenses;pending (new, etc.) /users/bill/expenses;pending /users/bill/expenses/123/line_items /users/bill/expenses/123/line_items/2 /2006/expenses/ /2006/expenses;submitted

Using HTTP to build REST Applications


Define the formats:
Neither HTTP nor REST mandate a single representation for data. A resource may have multiple representations:
XML, JSON, binary (e.g., jpeg), name/value pairs

Schema languages are not required (if even possible). Representations should be well-known media types (MIME types). Try and use up-stack media types:
Makes your resources maximally accessible, XHTML or Atom instead of vanilla XML.

Spring 2010

mark.baker@computer.org

Using HTTP to build REST Applications


Pick the operations:
HTTP has a constrained user interface (set of verbs/operations/methods):
GET, POST, PUT, DELETE, HEAD, OPTIONS (not widely supported), TRACE (not significant), CONNECT (not significant).

All of our resources will support GET!

Spring 2010

mark.baker@computer.org

Using HTTP to build REST Applications


GET returns a representation of the current state of a resource. GET is safe:
Does not change resource state, May trivially change server side state, e.g. log files,

GET is idempotent:
Multiple requests are the same as a single request, Might be impacted by concurrent operations.

NEVER violate these rule.

Spring 2010

mark.baker@computer.org

Using HTTP to build REST Applications


Highlight exceptional status codes:
HTTP has more response codes than 200 and 404 learn them:
Information: 1xx, Success 2xx, Redirection 3xx, Client Error 4xx, Server Error 5xx;

For GETs we will need:


200 OK, 204 No Content, 404 Not Found, Well need more later.

Spring 2010

mark.baker@computer.org

Using HTTP to build REST Applications


REST Frameworks:
It is possible and legitimate to build REST systems with any HTTP-enabled application environment. Few frameworks now, but more everyday:
RESTlet Ruby on Rails Django CherryPy JSR 311/JAX-RS Astoria Project Zero .NET 3.5 Tycho (Java, open source) (Ruby, open source) (Python, open source) (Python, open source) (Java) (.NET, Microsoft labs project) (Groovy/PHP, IBM incubator project) (aka Orcas, unreleased) (Reading system).

Spring 2010

mark.baker@computer.org

REST Concepts and Practices


Addressability:
Every resource that your application manages should be exposed via a URI, Every URI you provide is a de facto resource, code accordingly, The URI space is infinite, Multiple representations of a single resource should be uniquely addressable, URIs are understood by almost all software, URIs can be: written down, memorised, emailed, bookmarked, piped into other apps.

Spring 2010

mark.baker@computer.org

REST Concepts and Practices


On Statelessness:
Every request happens in isolation:
Client maintains application state, All information required by a resource is in the request, Server does not use information from previous requests.

The possible states of a server are also resources, and have URIs:
The 10th through Xth pending expense reports
/expenses;pending,start=10

Can be retrieved without first visiting the first page of expenses, No synchronized state needed, e.g. FTPs working directory.

Lights that are on at this moment: /lights/currently_on

Eliminates many failure conditions where clients may perform operations out of order.
Spring 2010 mark.baker@computer.org

REST Concepts and Practices


On Statelessness:
Stateless applications can be load-balanced, partitioned, scaled, cached:
More easily allows for active-active disaster recovery.

Sessions are to be avoided:


Sessions are servers maintaining client-side state, Message is no longer self-descriptive, Server may respond differently to identical requests based on session.

Server should forget about clients between requests:


No cookies, No session keys in URI or request data.

Be very careful if breaking the statelessness constraint:


Impacts reliability, scalability, performance.
Spring 2010 mark.baker@computer.org

REST Concepts and Practices


Self-descriptive messages:
Message semantics visible without looking at the message body:
Headers describing messages and content, Statelessness, Standard methods, Standard media types.

Enables support for intermediation:


Cache knows it can cache GETs, but not POSTs, Cache knows freshness information, Compression engine can choose best technique for content type, Gateway can reject requests for non-English content.

Spring 2010

mark.baker@computer.org

REST Concepts and Practices


Self-descriptive messages: representations and media types:
Try and use well-known media types:
Makes content more accessible, Part of the self-descriptive messaging constraint.

Avoid creating custom representations. There are too few business-oriented media types today:
Craft business messages into XHTML, and/or embed in Atom!

Incoming representations should be the same as outgoing representations:


A client should be able to GET, modify, and PUT a document, Server should discard any extraneous data.
Spring 2010 mark.baker@computer.org

REST Concepts and Practices


The Uniform Interface:
All resources present the same external interface, Creates a network:
Anyone can play to some degree, Encourages network effects.

HTTP verbs are constrained in how they impact resources:


Safety (GET):
Simply: No change to server-side state, Precisely: Client not responsible for changes to server-side state.

Idempotency (PUT, DELETE):


More than one request is the same as one request.

Developer is responsible for assuring these constraints, POST is not constrained.


Spring 2010 mark.baker@computer.org

REST Concepts and Practices


The Uniform Interface:
GET and POST are all you really need to be RESTful:
Get state / change state, PUT and DELETE are handy optimisations.

Avoid overloading POST.

Spring 2010

mark.baker@computer.org

REST Concepts and Practices


Reliable Messaging:
HTTP is an unreliable protocol:
No mechanism for determining if sent message was received.

But GET, PUT, and DELETE are intrinsically reliable:


GET is safe and idempotent, call it till you get a response, PUT and DELETE are idempotent, call them till you get a response.

POST is a problem:
Not safe or idempotent, A number of solutions have been developed, but none are widely in use POST Once Exactly (POE) and HTTPLR (Reliable Transmission).

Spring 2010

mark.baker@computer.org

REST, WS-*, and SOA


Why REST/HTTP is good:
Meets the requirements specified of it:
Scalable, high-performing, evolvable, visible, reliable, simple.

Uses existing infrastructure:


Cache engines, firewalls, SSL accelerators, monitoring, load balancers, etc.

Reach:
Low barrier to entry, Ubiquitous (programming languages, operating systems, servers, browsers, spreadsheets, news readers, mobile devices, etc.).

Addressable - URIs make the Web Interoperable. Extensible.


Spring 2010 mark.baker@computer.org

REST, WS-*, and SOA


Current REST Limitations:
Developer tooling is limited, Requires developers to think differently, Dearth of organised documentation, Security too limited, Some of HTTP's pre-existing syntax, Content negotiation does not quite work, POST is non-idempotent, Support for PUT and DELETE, Could use a PATCH method, Not natively asynchronous, Response messages do not indicate request,
mark.baker@computer.org

Spring 2010

REST, WS-*, and SOA


REST vs SOAP and WS-*
As a means for building out wide-scale, reusable distributed systems, WS-* is seriously flawed.
Flaw: Undesigned / without constraints:

Does not provably exhibit any non-functional requirement (scalability, etc.):


Empirical evidence suggests this is true! Not scalable or reliable: Cannot be partitioned, not stateless, Not performant: Cannot be cached, Not evolvable.

Abuses (tunnels over) HTTP (yet uses the term web services):
Unable to leverage any HTTP benefits, Requires a whole new investment in infrastructure.
Spring 2010 mark.baker@computer.org

REST, WS-*, and SOA


REST vs SOAP and WS-*
Flaw: Poorly specified:
Too many overly complex specifications, Solving problems no one has: e.g distributed transactions, and BPEL, Not very interoperable, even with just SOAP, Married too closely to XML Schema
Difficult, brittle Type systems dont work across languages

No versioning Trouble with binary data (SwA, DIME, MTOM) WSDL is the work of mad men UDDI: monstrously complex and unsuited for the job its deployed to do WS-Addressing: URIs done badly
mark.baker@computer.org

Spring 2010

REST, WS-*, and SOA


REST vs SOAP and WS-*
Flaw: Marketing:
Vendor wars, Over promised, over sold, and over due, Tools encourage backwards (code first) development, Tools discourage use of XML tooling: XPath, XSLT, XQuery, etc.

Flaw: Every endpoint is its own private network


Clients tightly bound to servers not evolvable, No reach, accessible by programmers only (barely), SOAP resources are not addressable:
Do not enrich the Web. Effectively not there, No notion of links: No spidering, search, bookmarking, tagging. etc., Every end point is a terminal point.

WS-Merits - WS-Security is OK.


Spring 2010 mark.baker@computer.org

REST, WS-*, and SOA


REST and SOA: SOA is not about technologies:
WS-*, REST, CORBA, etc. can be used,

Use REST instead of WS-*:


Infinitely simpler, More accessible, Leverages existing infrastructure, Actually works, Requires less governance.

SOA leverages a managed communication infrastructure (MCI):


XML gateways, SOA management systems, enterprise service busses

REST MCI equally available, battle hardened, already in place


Spring 2010 mark.baker@computer.org

REST Easy
Recommendations:
REST should be your default choice for distributed applications, REST is not a silver bullet. Use other solutions (e.g. Message-Oriented Middleware, WS-*) as requirements call for it:
MOM is good, Someday, not today, WS-* may make a "better MOM.

Use SOAP/WS-* to integrate with existing SOAP/WS-* applications,

Spring 2010

mark.baker@computer.org

You might also like