REST in Practice - Part I

76
REST in Practice REST in Practice REST in Practice REST in Practice Part I Part I Part I Part I Centro de Informática Universidade Federal de Pernambuco Universidade Federal de Pernambuco Vanilson Burégio Vanilson Burégio [www: vanilson.com] [email: [email protected] ] A t 2011 August2011

description

Part of this presentation were made by reusing the high quality material gently provided for educational purpose by Dr. Jim Webber, author of the book "REST in Practice".

Transcript of REST in Practice - Part I

Page 1: REST in Practice - Part I

REST in PracticeREST in PracticeREST in PracticeREST in PracticePart IPart IPart IPart ICentro de InformáticaUniversidade Federal de PernambucoUniversidade Federal de Pernambuco

Vanilson BurégioVanilson Burégio[www: vanilson.com] ‐ [email: [email protected] ]A t 2011August‐2011

Page 2: REST in Practice - Part I

Part of this presentation was based on the high qualityPart of this presentation was based on the high qualitymaterial gently provided by Dr. Jim Webber, author of thebook “REST in Practice: Hypermedia and Systemsbook REST in Practice: Hypermedia and SystemsArchitecture”, for educational purposes.

2

Page 3: REST in Practice - Part I

AgendaAgenda

• Motivation• Web Architecture• Introduction to REST• Introduction to REST• Practical Example• Web TunnelingCRUD b i• CRUD web services

3

Page 4: REST in Practice - Part I

MotivationMotivation

• The web has radically transformed the way we produce and share informationshare information– International ecosystem of application and sevices

• We can search, combine, aggregate, transform, replicate, cache and archive information that underpins today’s digital society!

• Today’s Web is in large part the HUMANWEBToday s Web is in large part the HUMAN WEB– Human users are the direct consumers of services offered by the 

majority of web applications

• How we might apply the Web’s underlying architectural i i l t b ildi di t ib t d t ( t iprinciples to building distributed systems (enterprise 

applications)? 

4

Page 5: REST in Practice - Part I

Web Web ArchitectureArchitecture

• A caotic place: mix of business, research government social andresearch, government, social, andindividual interests

• Anarchic architecture: thousands of simple, small‐scale interactionsbetween agents and resourcesthat use the founding 

h l i f HTTP d h URItechnologies of HTTP and the URI

5

Page 6: REST in Practice - Part I

Web Web ArchitectureArchitecture

• Principles and technologies

– URI and resources playing a  leading role

– Caches for scalability

– Services boundaries support• Isolation and Independent evolution of so at o a d depe de t e o ut o o

functionality• encouraging loose coupling

6

Page 7: REST in Practice - Part I

Web As Web As anan Application Application PlatformPlatform

• The most pervasive middleware!!D it th t f h d d l t th t h– Despite the amount of research and development that has gone into several platforms, none of them has managed to become as pervasive as the Web is today

• Web’s Middleware: set of widely deployed and commoditized elements: web servers that host resources, proxies, caches, content delivery networks,etc

• Together, these elements support the deployment of a l t l t k f t ith t ti tplanetary‐scale network of systems without resorting to 

intricate object models or complex middleware solutions.

7

Page 8: REST in Practice - Part I

Web As na Application Web As na Application PlatformPlatform... ... WhyWhy??

• The Web as a platform is the result of its architectural simplicity, the use of a widely implemented and agreed‐upon p y, y p g pprotocol (HTTP), and the pervasiveness of common representation formats

• Technology Support– It is supported by several development technologies and platforms

• Scalability and Performance– global deployment of networked applicationsglobal deployment of networked applications

• Loose Coupling– Services change without notification– There is no explicity mechanisms to support information integrity– HTTP uses status code... Broken links.

8

Page 9: REST in Practice - Part I

Web As na Application Web As na Application PlatformPlatform... ... WhyWhy??

• Business ProcessesSt t f d l d– States of a process modeled as resources

– None of the work to capture business processes (BPEL, *WS‐Choreography..) really embraced the Web’s achitectural principals

• Consistency and Uniformity– Principle of uniformity: HTML, XML and other formats are all just

resources representation

9

Page 10: REST in Practice - Part I

HH tt b ildib ildi tt t it iHowHow to to buildingbuilding computercomputer systems in systems in aa webweb‐‐centriccentric wayway ((embracingembracing thethea a webweb centriccentric wayway ((embracingembracing thetheweb’sweb’s architecturalarchitectural principalsprincipals)?)?

10

Page 11: REST in Practice - Part I

REST!! REST!! ButBut, , whatwhat does it does it meanmean??

11

Page 12: REST in Practice - Part I

REST REST ‐‐ REpresentationalREpresentational StateState TransferTransfer

• REST is an Architectural Style– REST is a set of principles that define how Web standards, such as 

HTTP and URIs, are supposed to be used

• REST isn’t…Just pretty URIs– Just pretty URIs

– Just XML or JSONURI t l t– URI templates

– AJAX applications

12

Page 13: REST in Practice - Part I

KeyKey REST REST PrinciplesPrinciples

• If you adhere to REST principles while designing your application you will end up with a system that exploits theapplication, you will end up with a system that exploits the Web’s architecture to your benefit

• Key Principlesd f f ( )– Identification of resources (URI)

– Manipulation of resources through REPRESENTATIONS– Hypermedia as the engine of application stateHypermedia as the engine of application state– Uniform Interface constraint

13

Page 14: REST in Practice - Part I

ThinkingThinking in in ResourcesResources......

• Resources are the fundamental building blocks of b b dweb‐based systems

– A resource is anything we expose to the Web, from a document or video clip to a business process or devicevideo clip to a business process or device

Al t thi b d l d d• Almost anything can be modeled as a resource and then made available for manipulation over the 

t knetwork

14

Page 15: REST in Practice - Part I

ResourcesResources andand identifiersidentifiers• To use a resource we need both to be able to identify it on the network and to have some 

means of manipulating it

• The web provides the Uniform Resource Identifier (URI)– The relationship between URIs and resources is many‐to‐one– There’s no limit on the number of URIs that can refer to a resource, and it is in fact quite common 

for a resource to be identified by numerous URIs

• A URI takes the form <scheme>:<scheme specific structure>• A URI takes the form <scheme>:<scheme‐specific‐structure>– The scheme defines how the rest of the identifier is to be interpreted

15

Page 16: REST in Practice - Part I

ResourcesResources andand identifiersidentifiers

Terms used on the Web to refer to identifiers

16

Terms used on the Web to refer to identifiers

Page 17: REST in Practice - Part I

ResourceResource RepresentationsRepresentations• Each identifier is associated with one or more representations

• A Representation is a transformation or a view of a resource’s state at an instantA Representation is a transformation or a view of a resource s state at an instant in time

• Resource representation formats– The resource’s view is encoded in one or more transferable formats, such as XHTML, Atom, XML, 

JSON, plain text, comma‐separated values, MP3, or JPEG.

• The Web does not support pointers! e eb does ot suppo t po te s!– Access to a resource is always mediated by way of its representations web components exchange 

representations; they never access the underlying resource directly

Human‐friendly

17machine‐friendly

Page 18: REST in Practice - Part I

ResourceResource RepresentationsRepresentations

• Content negotiation mechanismThere is a misconception that different resource representations– There is a misconception that different resource representations should each have their own URI (notion popularized by the Rails framework)• resource terminate URIs with .xml or .json to indicate a preferred format 

http://restbucks.com/order.xml or http://example.org/order.json

Consumers can negotiate for specific representation formats using HTTP Accept request header with a list f di h ’ dof media types they’re prepared to process

18Multiple resource representations addressed by a single URI

Page 19: REST in Practice - Part I

Hypermedia as the engine of application Hypermedia as the engine of application state (state (HATEOAS)HATEOAS)state (state (HATEOAS)HATEOAS)• The principle: Use links to refer to identifiable resources 

wherever possiblewherever possible– A distributed application makes forward progress by transitioning 

from one state to another, just like a state machine. – The difference from traditional state machines: the possible states 

and the transitions between them are not known in advance. Instead as the application reaches a new state the next possibleInstead, as the application reaches a new state, the next possible transitions are discovered.

– Link Things to each other…

19

Page 20: REST in Practice - Part I

Hypermedia as the engine of application Hypermedia as the engine of application state (state (HATEOAS)HATEOAS)state (state (HATEOAS)HATEOAS)• REST describes the Web as a distributed hypermedia 

application whose linked resources communicate byapplication whose linked resources communicate by exchanging representations of resource state– Links act as embedded identifiers of the states to which theLinks act as embedded identifiers of the states to which the 

application can transition

20

Page 21: REST in Practice - Part I

UniformUniform Interface Interface ConstraintConstraint

• The set of verbs supported by HTTP—GET, POST, PUT, DELETE, OPTIONS HEAD TRACE CONNECT and PATCH—forms a sufficientlyOPTIONS, HEAD, TRACE, CONNECT, and PATCH—forms a sufficiently general‐purpose protocol to support a wide range of solutions

• Use standard Methods– GET: retrieve information, possibly cached– PUT: Update or create with known ID– POST: Create or append sub‐resource

DELETE (l i ll )– DELETE: (logically) remove

21

Page 22: REST in Practice - Part I

ExampleExample: online shop: online shop

• Functionalities– list orders – get customer details– list customers– get order details

g

– Update customer– Cancel order

– List orders for customer– Delete customer

Cancel order– Add customer– Submit order

– Add order item– Submit order– Update order

WhichWhich [[web] web] servicesservices couldcould bebe createdcreated??22

[[ ]]

Page 23: REST in Practice - Part I

Example: online shopExample: online shop

• One possibility: two ServicesThinkingThinking in REST in REST 

p ygg

principlesprinciples......

HowHow to design in to design in termstermsofof resourcesresources withwith ananuniformuniform interface?interface?uniformuniform interface?interface?

23

Page 24: REST in Practice - Part I

HowHow to design to design withwith anan uniformuniform interface?interface?

• The set of verbs supported by HTTP forms a sufficiently general‐purpose protocol to support a wide range of solutionspurpose protocol to support a wide range of solutions

GET: retrieve information, possibly cached PUT: Update or create with known ID    POST: Create or append sub‐resource DELETE: (logically) remove

Which resourcesWhich resourcescould beconsidered? 

How to map thef i li i ?functionalities?

24

Page 25: REST in Practice - Part I

Approach Approach differencesdifferences

• The first approach

Many

Many Very few(one by service)

25

Page 26: REST in Practice - Part I

Approach Approach differencesdifferences

• The second approach

Many

ManyVery few(FIXED)

26

Page 27: REST in Practice - Part I

Richardson maturity model for the Web, Richardson maturity model for the Web, not just REST...not just REST...not just REST...not just REST...• REST is a brilliant 

architectural stylearchitectural style• But the Web allows for 

more than just RESTfuljsystems

• There’s a spectrum of maturity of service stylesmaturity of service styles– From completely bonkers 

to completely RESTful• We’ll use the Richardson 

maturity model to frame these kinds of discussionsthese kinds of discussions– Level 0 to Level 3– Web‐ignorant to RESTful!

Page 28: REST in Practice - Part I

Web TunnellingWeb Tunnelling

Page 29: REST in Practice - Part I

Web TunnellingWeb Tunnelling

• Web Services tunnel SOAP over HTTP– Using the Web as a transport only– Ignoring many of the features for robustness theIgnoring many of the features for robustness the Web has built in

• Many Web people do the same!• Many Web people do the same!– URI tunnelling, POX approaches are the most popular styles on today’s Web

–Worse than SOAP! But they claim to 

• Less metadata!y

be “lightweight” and RESTful

Page 30: REST in Practice - Part I

Richardson Model Level 1Richardson Model Level 1

• Lots of URIs– But really has a more level 0 mindset

• Doesn’t understand HTTP– Other than as a transport

• No hypermedia

Page 31: REST in Practice - Part I

URI Tunnelling PatternURI Tunnelling Pattern

• Web servers understand URIs• URIs have structure• Methods have signatures• Can match URI structure to method signaturehttp://restbucks.com/PlaceOrder?coffee=latte&size=large&milk=whole&comsume‐location=to‐go

service method argumentsmaps to

public OrderConfirmation PlaceOrder(Order order){

...}

Page 32: REST in Practice - Part I

On The WireOn The Wire

Page 33: REST in Practice - Part I

ServerServer‐‐Side URI Tunnelling ExampleSide URI Tunnelling Examplepublic void ProcessGet(HttpListenerContext context){// Parse the URI// Parse the URIOrder order = ParseUriForOrderDetails(context.Request.QueryString);

string response = string.Empty;

if (order != null){

// Process the order by calling the mapped methodvar orderConfirmation = RestbucksService.PlaceOrder(order);

response = "OrderId=" + orderConfirmation.OrderId.ToString();}else{{response = "Failure: Could not place order.";

}

// Write to the response stream using (var sw = new StreamWriter(context.Response.OutputStream)){sw.Write(response);

}}}

Page 34: REST in Practice - Part I

ClientClient‐‐Side URI TunnellingSide URI Tunnellingpublic OrderConfirmation PlaceOrder(Order order){// Create the URIvar sb = new StringBuilder("http://restbucks com/PlaceOrder?");var sb = new StringBuilder("http://restbucks.com/PlaceOrder?");

sb.AppendFormat("coffee={0}", order.Coffee.ToString());sb.AppendFormat("&size={0}", order.Size.ToString());sb.AppendFormat("&milk={0}", order.Milk.ToString());pp ( { } , g());sb.AppendFormat("&consume-location={0}", order.ConsumeLocation.ToString());

// Set up the GET requestvar request = HttpRequest.Create(sb.ToString()) as HttpWebRequest;request.Method = "GET";

// Get the responsevar response = request.GetResponse();

// Read the contents of the responseOrderConfirmation orderConfirmation = null;using (var sr = new StreamReader(response.GetResponseStream())){{var str = sr.ReadToEnd();

// Create an OrderConfirmation object from the responseorderConfirmation = new OrderConfirmation(str);

}return orderConfirmation;

}

Page 35: REST in Practice - Part I

URI Tunnelling StrengthsURI Tunnelling Strengths

• Very easy to understand• Great for simple procedure‐calls• Simple to code• Simple to code– Do it with the servlet API, HttpListener, IHttpHandler, RAILS, whatever!

• Interoperablep– It’s just URIs!

Page 36: REST in Practice - Part I

URI Tunnelling WeaknessesURI Tunnelling Weaknesses• It’s brittle RPC!• Tight coupling, no metadata– No typing or “return values” specified in the URI

• Not robust – have to handle failure cases manually

• No metadata support– Construct the URIs yourself, map them to the functionConstruct the URIs yourself, map them to the function manually

• You typically use GET (prefer POST)You typically use G T (prefer POST)– OK for functions, but against the Web for procedures with side‐affects

Page 37: REST in Practice - Part I

POX PatternPOX Pattern

• Web servers understand how to process requests with bodies– Because they understand formsBecause they understand forms

• And how to respond with a body’– Because that’s how the Web works

• POX uses HTTP POST to transfer XML documents btw systems

Page 38: REST in Practice - Part I

Richardson Model Level 0Richardson Model Level 0

• Single well‐known endpoint– Not really URI friendly

• Doesn’t understand HTTP– Other than as a transport

• No hypermedia

Page 39: REST in Practice - Part I

POX on the WirePOX on the Wire

POST /Pl O d HTTP/1 1

restbucks application domainclient application domain

POST /PlaceOrder HTTP/1.1Content‐Type:  application/xmlHost: restbucks.comContent‐Length:  361

<Order xmlns="http://restbucks.com"><CustomerId>abcd</CustomerId><ConsumeAt>takeAway</ConsumeAt><Items><Item>

<Name>latte</Name><Quantity>1</Quantity><Milk>whole</Milk><Size>small</Size>

</Item><Item>

<Name>cookie</Name> <Kind>chocolate‐chip</Kind><Quantity>2</Quantity>

</Item></Items>

</Order>

HTTP/1.1 200 OKContent‐Length:  93Content‐Type:  application/xml;  charset=utf‐8Server: Microsoft‐HTTPAPI/2.0Date: Mon, 04 Aug 2008 18:16:49 GMT

<OrderConfirmation xmlns="http://restbucks.com"><OrderId>1234</OrderId>

</OrderConfirmation>

Page 40: REST in Practice - Part I

POX ArchitecturePOX Architecture

b k li i d ili li i d i restbucks application domainclient application domain

jimwaiter

baristasavas

ian

client side

jim

server side

cashierLocal method call Local method callLocal method call 

returnLocal method 

return

1 5610

client‐side dispatcher

server‐side dispatcher

XML document into HTTP client

XML document from HTTP client 

XML document into HTTP response

XML document from HTTP client

200 OK + XML

2

479

HTTP client HTTP serverHTTP POST + XML 

payload

200 OK + XML payload

3

8

object dispatcher code communication

3

Page 41: REST in Practice - Part I

.Net POX Service Example.Net POX Service ExampleF h W b

private void ProcessRequest(HttpListenerContext context){string verb = context.Request.HttpMethod.ToLower().Trim();

From the Web server

g q pswitch (verb){

case "post":{// Everything's done with post in this case

Check HTTP Verb (we want POST)// Everything s done with post in this case

XmlDocument request = new XmlDocument();request.Load(XmlReader.Create(context.Request.InputStream));

want POST)Dispatch it for processing

XmlElement result = MyApp.Process(request.DocumentElement);byte[] returnValue = Utils.ConvertUnicodeString(Constants.Xml.XML_DECLARATION + result.OuterXml);

Turn the HTTP body into an XML document for

context.Response.OutputStream.Write(returnValue, 0, returnValue.Length);

break;

XML document for processing

break;} ...

Get XML result, and get bytes Return XML bytes to client

Page 42: REST in Practice - Part I

Java POX Java POX ServletServletpublic class RestbucksService extends HttpServlet {

@Overrideprotected void doPost(HttpServletRequest request,

HttpServletResponse response)throws ServletException, IOException {throws ServletException, IOException {

// Initialization code omitted for brevitytry {

requestReader = request getReader();requestReader request.getReader();responseWriter = response.getWriter();

String xmlRequest = extractPayload(requestReader);

Order order = createOrder(xmlRequest);

OrderConfirmation confirmation = restbucksService.placeOrder(order);

embedPayload(requestWriter, confirmation.toString());

} finally {// Cl d itt d f b it// Cleanup code omitted for brevity

}}

Page 43: REST in Practice - Part I

C# POX Client ExampleC# POX Client Examplepublic OrderConfirmation PlaceOrder(string customerId, Item[] items){

// Serialize our objects// Serialize our objectsXmlDocument requestXml = CreateXmlRequest(customerId, items);var client = new WebClient();

var ms = new MemoryStream();var ms = new MemoryStream();requestXml.Save(ms);

client.Headers.Add("Content-Type", "application/xml");

ms = new MemoryStream(client.UploadData("http://restbucks.com/PlaceOrder", null, ms.ToArray()));

var responseXml = new XmlDocument();responseXml.Load(ms);return CreateOrderConfirmation(responseXml);

}}

Page 44: REST in Practice - Part I

Java Apache Commons ClientJava Apache Commons Clientpublic class OrderingClient {

private static final String XML HEADING = "<?xml

private String sendRequestPost(Stringrequest, String uri)

thprivate static final String XML_HEADING = <?xml version=\"1.0\"?>\n";

private static final String NO_RESPONSE = "Error: No response.";

public String placeOrder(String customerId

throws IOException, HttpException {PostMethod method = new PostMethod(uri);method setRequestHeader("Content-public String placeOrder(String customerId,

String[] itemIds)throws Exception {

// XML string creation omitted for brevity//

method.setRequestHeader( Contenttype", "application/xml");method.setRequestBody(XML_HEADING + request);String responseBody = NO RESPONSE;// ...

String response = sendRequestPost(request, "http://restbucks.com/PlaceOrder");

l

g p y _try {

new HttpClient().executeMethod(method);

responseBody = new Document xmlResponse = DocumentBuilderFactory.newInstance()

.newDocumentBuilder().parse(new InputSource(new

StringReader(response)));

String(method.getResponseBody(), "UTF-8");} finally {

method.releaseConnection();StringReader(response)));

// XML response handling omitted for brevity}

}return responseBody;

}}

Page 45: REST in Practice - Part I

POX StrengthsPOX Strengths

• Simplicity – just use HTTP POST and XML• Re‐use existing infrastructure and libraries• Interoperable• Interoperable– It’s just XML and HTTP

• Can use complex data structures– By encoding them in XMLBy encoding them in XML

Page 46: REST in Practice - Part I

POX WeaknessesPOX Weaknesses

• Client and server must collude on XML payload– Tightly coupled approachTightly coupled approach

• No metadata support’– Unless you’re using a POX toolkit that supports 

WSDL with HTTP binding (like WCF)

• Does not use Web for robustness• Does not use SOAP + WS‐* for robustness• Does not use SOAP + WS‐  for robustness either

Page 47: REST in Practice - Part I

CRUDWeb Services: EmbracingCRUDWeb Services: EmbracingCRUD Web Services: Embracing CRUD Web Services: Embracing HTTP as an Application ProtocolHTTP as an Application ProtocolHTTP as an Application ProtocolHTTP as an Application Protocol

Page 48: REST in Practice - Part I

Using the WebUsing the Web• URI tunnelling and POX use the Web as a t ttransport– Just like SOAP without metadata support

• CRUD services begin to use the Web’s coordination support

• But the Web is more than transport– Transport, plus

HTTPHeadersStatus Codes

– Metadata, plus– Fault model, plus

Status CodesUniform InterfaceCaches, proxies, 

– Component model, plus– Runtime environment, plus...

, p ,servers, etc

p

Page 49: REST in Practice - Part I

CRUD Resource LifecycleCRUD Resource Lifecycle

• The resource is created with POST• It’s read with GET• And updated via PUT• And updated via PUT• Finally it’s removed using DELETE

Page 50: REST in Practice - Part I

Richardson Model Level 2Richardson Model Level 2

• Lots of URIs• Understands HTTP!• No hypermediaNo hypermedia

Page 51: REST in Practice - Part I

Create with POSTCreate with POST

POST /orders<order … />

201 CreatedLocation: /1234

Ordering Client

Location: …/1234

400 Bad RequestOrdering ServiceClient 400 Bad Request Service

500 Internal Error

Page 52: REST in Practice - Part I

POST SemanticsPOST Semantics

• POST creates a new resource• But the server decides on that resource’s URI• Common human Web example: posting to• Common human Web example: posting to Web log– Server decides URI of posting and any comments made on that post

• Programmatic Web example: creating a new employee recordemployee record– And subsequently adding to it

Page 53: REST in Practice - Part I

POST RequestPOST RequestPOST /orders HTTP/1.1Host: restbucks.com

Verb, path, and HTTP version

Content-Type:application/vnd.restbucks+xmlContent-Length: 225 Restbucks‐specific XML 

content<order xmlns="http://schemas.restbucks.com/order">

<location>takeAway</location><items>

content

<items><item>

<name>latte</name>< tit >1</ tit ><quantity>1</quantity><milk>whole</milk><size>small</size>

Content(again Restbucks XML)

</item></items>

</order>

(again Restbucks XML)

Page 54: REST in Practice - Part I

POST ResponsePOST ResponseHTTP/1.1 201 CreatedLocation: /orders/1234

Page 55: REST in Practice - Part I

POST Implementation with a POST Implementation with a ServletServletprotected void doPost(HttpServletRequest request,

HttpServletResponse response) {t {try {Order order = extractOrderFromRequest(request);String internalOrderId = OrderDatabase.getDatabase().saveOrder(order);response.setHeader("Location", computeLocationHeader(request,response.setHeader( Location , computeLocationHeader(request,

internalOrderId));response.setStatus(HttpServletResponse.SC_CREATED);

} catch(Exception ex) {response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

}}

Page 56: REST in Practice - Part I

Read with GETRead with GET

GET /orders/1234

200 OK<order … />

Ordering Client 404 Not Found

Ordering Service

500 I t l E500 Internal Error

Page 57: REST in Practice - Part I

GET SemanticsGET Semantics

• GET retrieves the representation of a resource• Should be idempotent– Shared understanding of GET semantics– Shared understanding of GET semantics– Don’t violate that understanding!

Page 58: REST in Practice - Part I

GET ExemplifiedGET Exemplified

GET /orders/1234 HTTP/1.1Accept: application/vnd.restbucks+xmlHost: restbucks.com

Page 59: REST in Practice - Part I

GET ResponseGET ResponseHTTP/1.1 200 OKContent-Length: 232Content-Type: application/vnd.restbucks+xmlDate: Wed, 19 Nov 2008 21:48:10 GMT

d l "htt // h tb k / d "<order xmlns="http://schemas.restbucks.com/order"><location>takeAway</location><items>

<item><item><name>latte</name><quantity>1</quantity><milk>whole</milk>milk whole /milk<size>small</size>

</item></items><status>pending</pending>

</order>

Page 60: REST in Practice - Part I

When GET Goes wrongWhen GET Goes wrong• Simple!– Just 404 – the resource is no longer available

/1 1 404 dHTTP/1.1 404 Not FoundContent-Type: application/vnd.restbucks+xmlContent-Length: 952Date: Sat, 20 Dec 2008 19:01:33 GMT

• Are you sure?– GET again!

• GET is safe and idempotent– Great for crash recovery scenarios!y

Page 61: REST in Practice - Part I

Idempotent BehaviourIdempotent Behaviour• An action with no side affects– Comes from mathematics– Comes from mathematics

• In practice means two things:– A safe operation is one which changes no state at allA safe operation is one which changes no state at all

• E.g. HTTP GET– An idempotent operation is one which updates state in an absolute wayabsolute way• E.g. x = 4 rather than x += 2

• Web‐friendly systems scale because of safetyy y y– Caching!

• And are fault tolerant because of idempotent b h ibehaviour– Just re‐try in failure cases

Page 62: REST in Practice - Part I

GET JAXGET JAX‐‐RS ImplementationRS Implementation@Path("/")public class OrderingService {

@GET@Produces("application/xml")@Path("/{orderId}")public String getOrder(@PathParam("orderId") String orderId) {public String getOrder(@PathParam( orderId ) String orderId) {try {Order order = OrderDatabase.getDatabase().getOrder(orderId);if (order != null) {return xstream.toXML(order);

} else {throw new WebApplicationException(404);

}} catch (Exception e) {throw new WebApplicationException(500);

}}}// Remainder of implementation omitted for brevity

}

Page 63: REST in Practice - Part I

Update with PUTUpdate with PUTPUT /orders/1234<order … /><order … />

200 OK200 OK

Ordering Client

404 Not FoundOrdering Service

409 Conflict

500 Internal Error

Page 64: REST in Practice - Part I

PUT SemanticsPUT Semantics

• PUT creates a new resource but the client decides on the URI– Providing the server logic allows itProviding the server logic allows it

• Also used to update existing resources by iti th i loverwriting them in‐place

• PUT is idempotentp–Makes absolute changes

• But is not safe• But is not safe– It changes state!

Page 65: REST in Practice - Part I

PUT RequestPUT Request

PUT /orders/1234 HTTP/1 1PUT /orders/1234 HTTP/1.1Host: restbucks.comContent-Type: application/xmlContent-Length: 386

<order xmlns="http://schemas.restbucks.com/order"><location>takeAway</location><items>

<item><milk>whole</milk><name>latte</name><quantity>2</quantity><size>small</size>

</item><item>

<milk>whole</milk>

Updated content 

<name>cappuccino</name><quantity>1</quantity><size>large</size>

</item></items><status>preparing</preparing>

</order>

Page 66: REST in Practice - Part I

PUT ResponsePUT ResponseHTTP/1.1 200 OKDate: Sun, 30 Nov 2008 21:47:34 GMTContent-Length: 0g

Minimalist response contains no entity body

Page 67: REST in Practice - Part I

When PUT goes wrongWhen PUT goes wrong• If we get 5xx error, or 

4 i lHTTP/1.1 409 ConflictDate: Sun, 21 Dec 2008 16:43:07 GMTC t t L th 382some 4xx errors simply 

PUT again!PUT i id t t

Content-Length:382

<order xmlns="http://schemas.restbucks.com/order">

– PUT is idempotent• If we get errors indicating incompatible

<location>takeAway</location><items>

<item><milk>whole</milk>

/indicating incompatible states (409, 417) then do some

<name>latte</name><quantity>2</quantity><size>small</size>

</item><item>do some 

forward/backward compensating work

<item><milk>whole</milk><name>cappuccino</name><quantity>1</quantity><size>large</size>p g

– And maybe PUT againg /

</item></items><status>served</status>

</order>

Page 68: REST in Practice - Part I

Remove with DELETERemove with DELETEDELETE /orders/1234

200 OK200 OK

Ordering Client

404 Not FoundOrdering Service

405 Method Not Allowed

500 Service Unavailable

Page 69: REST in Practice - Part I

DELETE SemanticsDELETE Semantics

• Stop the resource from being accessible– Logical delete, not necessarily physical

• RequestRequestDELETE /orders/1234 HTTP/1.1Host: restbucks.com

• ResponsepHTTP/1.1 200 OKContent Length: 0Content-Length: 0Date: Tue, 16 Dec 2008 17:40:11 GMT

Page 70: REST in Practice - Part I

When DELETE goes wrongWhen DELETE goes wrong

• Simple case, DELETE again!– Delete is idempotent!– DELETE once, DELETE 10 times has the sameDELETE once, DELETE 10 times has the same effect: one deletion

HTTP/1.1 404 Not FoundContent-Length: 0Date: Tue, 16 Dec 2008 17:42:12 GMT

Page 71: REST in Practice - Part I

When DELETE goes Really WrongWhen DELETE goes Really Wrong• Some 4xx responses i di h d l i

HTTP/1.1 409 ConflictContent-Length: 379D t T 16 D 2008 17 53 09 GMTindicate that deletion 

isn’t possibleTh t t f th

Date: Tue, 16 Dec 2008 17:53:09 GMT

<order xmlns="http://schemas.restbucks.com/order">

– The state of the resource isn’t compatible

– Try forward/backward

<location>takeAway</location><items>

<item><name>latte</name>

i / iTry forward/backward compensation instead

<milk>whole</milk><size>small</size><quantity>2</quantity>

</item><item><item>

<name>cappuccino</name><milk>skim</milk><size>large</size><quantity>1</quantity>q y /q y

</item></items><status>served</status>

</order>

Can’t delete an order that’s 

already served

Page 72: REST in Practice - Part I

CRUD does not mean Worthless

Page 73: REST in Practice - Part I

CRUD is Good?CRUD is Good?• CRUD is good– But it’s not great– But it s not great

• CRUD‐style services use some HTTP features• But the application model is limitedBut the application model is limited

– Only suitable to CRUD Scenarios– Suits database‐style applications– Hence frameworks like Microsoft’s Astoria

• CRUD has limitations– CRUD ignores hypermedia– CRUD encourages tight coupling through URI templates– CRUD encourages server and client to collude– CRUD encourages server and client to collude

• The Web supports more sophisticated patterns than CRUD!

Page 74: REST in Practice - Part I

Research ActivityResearch Activity

• Compare:p– REST Vs SOAP– REST Vs SOAREST Vs WS *– REST Vs WS‐*

• Send a report to [email protected]• Discussion on the next class!!

Page 75: REST in Practice - Part I

Next class: Hypermedia and Next class: Hypermedia and RESTf lRESTf l S iS iRESTfulRESTful ServicesServices

Page 76: REST in Practice - Part I

ReferencesReferences• REST in Practice – Hypermedia and Systems Architecture

Jim Webber, Savas Parastatidis, Ian RobinsonJim Webber, Savas Parastatidis, Ian RobinsonPublished by O’Reilly, 2010

• REST in Practice ‐ A Tutorial on Web‐based ServicesJim Webber, Savas Parastatidis, Ian RobinsonPresentation for Universities, shared by Jim Webber

• Somes slides adapted from a presentation for Universities (REST in l b b d ) h d b Ji W bbPractice ‐ A Tutorial on Web‐based Services) shared by Jim Webber  

[http://jim.webber.name]

• A Brief Introduction to REST http://www.infoq.com/articles/rest‐introduction