rest overview

30
REST For Web Services Course, Fall 2005 Henning Niss IT University of Copenhagen Lecture 7 Henning Niss (ITU) REST Lecture 7 1 / 34

Upload: swamy-g

Post on 04-Jul-2015

2.349 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Rest Overview

REST For Web ServicesCourse, Fall 2005

Henning Niss

IT University of Copenhagen

Lecture 7

Henning Niss (ITU) REST Lecture 7 1 / 34

Page 2: Rest Overview

Material

I Main material (curriculum / “pensum”):I Fielding & Taylor: Principled Design of the Modern Web

Architecture, ACM Transactions on Internet Technology, Vol 2, No.2, May 2002, pages 115-150.http://www.ics.uci.edu/˜taylor/documents/2002-REST-TOIT.pdf

I Supplementary material:I REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.plI Paul Prescod: Second Generation Web Services, xml.com,

February 2002.http://webservices.xml.com/pub/a/ws/2002/02/06/rest.html

I Roger L. Costello: Building Web Services the REST Way, July 2002.http://www.xfront.com/REST-Web-Services.html

Henning Niss (ITU) REST Lecture 7 2 / 34

Page 3: Rest Overview

REST Overview

Overview

REST Overview

Example: RESTful Web services

The REST architectural style

Example: REST in the Joke server

REST Overview

Example: RESTful Web services

The REST architectural style

Example: REST in the Joke server

Henning Niss (ITU) REST Lecture 7 3 / 34

Page 4: Rest Overview

REST Overview

Introduction

REST is an architectural style.

I “packaged set of architectural design decisions”,

I a software architecture abstracts runtime elements of a system.

Goals:

I idealized model of interactions within a Web application,

I function as guiding principles to avoid flaws,

I minimize network latency and communication,

I maximize independence and scalability.

Most prominent example: the modern Web.

Focus today: REST from a Web services perspective.

Henning Niss (ITU) REST Lecture 7 4 / 34

Page 5: Rest Overview

REST Overview

REST-based Web services

Very high-level description of REST-based Web services:

resource-centric XML-over-HTTP services.

I endpoints are resources;

I endpoints are accessible via standard HTTP;

I endpoints are represented in XML.

Henning Niss (ITU) REST Lecture 7 5 / 34

Page 6: Rest Overview

Example: RESTful Web services

Applying REST — example

The successful company Parts Depot, Inc sells many different partsto many customers.

They would like well-designed Web services for this.

Parts Depot Web services:

I get list of parts;

I get detailed part information;

I submit purchase orders (PO).

Example due to R.L. Costello: Building Web Services the REST Way.

Henning Niss (ITU) REST Lecture 7 7 / 34

Page 7: Rest Overview

Example: RESTful Web services

Getting a part list

The list of parts available from Parts Depot is a resource:

I a resource is identified via a URI;

I resource representations are available via standard HTTP GET:

GET http://www.parts-depot.com/parts HTTP/1.1

I representations may be adapted to consumer:

<?xml version="1.0"?><p:Parts xmlns:p="http://www.parts-depot.com"

xmlns:xl="http://www.w3.org/1999/xlink"><Part id="0345" xl:href="http://www.parts-depot.com/parts/0345"/><Part id="0346" xl:href="http://www.parts-depot.com/parts/0346"/><Part id="0347" xl:href="http://www.parts-depot.com/parts/0347"/><Part id="0348" xl:href="http://www.parts-depot.com/parts/0348"/>

</p:Parts>

I a representation typically contains links to other resources.

Henning Niss (ITU) REST Lecture 7 8 / 34

Page 8: Rest Overview

Example: RESTful Web services

Getting part information

Detailed part information is also a resource identified with a URL.

I getting detailed information:

GET http://www.parts-depot.com/parts/0346 HTTP/1.1

I representation:

<?xml version="1.0"?><p:Part xmlns:p="http://www.parts-depot.com"

xmlns:xl="http://www.w3.org/1999/xlink"><Part-ID>0346</Part-ID><Name>Widget-A</Name><Desc>This part is used within the frap assembly</Desc><Spec xl:href="http://www.parts-depot.com/parts/0346/spec"/><UnitCost currency="USD">0.10</UnitCost>

</p:Part>

I how representation is generated is unspecified;

I logical URI (not necessarily static pages).

Henning Niss (ITU) REST Lecture 7 9 / 34

Page 9: Rest Overview

Example: RESTful Web services

Submitting a purchase order

To order a part, the client submits a purchase order.

I an order submitted using standard HTTP POST;

I the order is an XML document

<?xml version="1.0"?><p:Order xmlns:p="http://www.parts-depot.com"

xmlns:xl="http://www.w3.org/1999/xlink"><Part xl:href="http://www.parts-depot.com/parts/0346"/><Quantity>10</Quantity><Date>2005-10-11</Date>...

</p:Order>

I an order is shared information between Parts Depot and client;

I the Web service returns a URI for the submitted order;

I the client may delete the order using HTTP DELETE.

Henning Niss (ITU) REST Lecture 7 10 / 34

Page 10: Rest Overview

Example: RESTful Web services

Assessment (example)

Salient points of the example:

I focus on resources (resource-centric vs API-centric);

I resources are identified using URIs (“name everything”);

I resources are connected through links (“reveal gradually”);

I resources may have different representations (HTML, XML, . . . );

I based on standard technology (URI, HTTP, XML, . . . );

I separation of updatable and immutable resources (POST & GET).

Henning Niss (ITU) REST Lecture 7 11 / 34

Page 11: Rest Overview

The REST architectural style

The name REST

The name “Representational State Transfer” is intended toevoke an image of how a well-designed Web applicationbehaves: a network of Web pages forms a virtual statemachine, allowing a user to progress through theapplication by selecting a link or submitting a shortdata-entry form, with each action resulting in a transition tothe next state of the application by transferring arepresentation of that state to the user.

(Fielding & Taylor, 2002)

Henning Niss (ITU) REST Lecture 7 13 / 34

Page 12: Rest Overview

The REST architectural style

WWW Requirements

The major goal of the Web was to be a shared information space forpeople and machines to communicate.

I Low entry-barrier.

I Extensibility.

I Distributed hypermedia.

I Internet scale (scalable & independent).

REST is an architectural style for “architecting the Web”:

I “capture” the success of the Web;

I guide future extensions.

Henning Niss (ITU) REST Lecture 7 14 / 34

Page 13: Rest Overview

The REST architectural style

REST Constraints (1)

REST consists of a number of architectural constraints:

I client/server constraint:

, separation of concerns, independent evolution of components;

I stateless constraint:

, visibility (single request reveals everything), reliability (easier to recover from failures), scalability (server does not commit resources to each request)/ degrades network performance (by requiring large requests);

I caching constraint:

, improves network efficiency (eliminates interactions), clients have the “right” to reuse cacheable data/ degrades reliability (due to stale data);

Henning Niss (ITU) REST Lecture 7 15 / 34

Page 14: Rest Overview

The REST architectural style

REST Constraints (2)

I uniform interface constrain:

, general component interface, implementations decoupled from interfaces/ degrades efficiency (to adapt to the uniform interface);

I layered system constraint:

, architecture can be composed hierarchically, overall system complexity bounded/ added overhead;

I (code-on-demand)

Henning Niss (ITU) REST Lecture 7 16 / 34

Page 15: Rest Overview

The REST architectural style

Architectural elements

Three classes of architectural elements:

I processing elements (components);

I data elements (resources);

I connecting elements (connectors).

REST is concerned with architecture; for example

I component implementation left to service providers;

I protocol syntax left to HTTP and XML.

Henning Niss (ITU) REST Lecture 7 17 / 34

Page 16: Rest Overview

The REST architectural style

Resources

A resource is “anything that can be named”.

I a document,

I “today’s weather in Los Angeles”,

I a collection of other resources.

Formally: membership function mapping a time t to a set of values(“representations”).

I the empty set (resource not yet realized),

I an XML representation and a HTML representation,

I a(nother) resource identifier (“redirect”).

Resources identified or named by resource identifiers (URIs).

The identifier (not the content) captures the “semantics” of theresource.

Henning Niss (ITU) REST Lecture 7 18 / 34

Page 17: Rest Overview

The REST architectural style

Representations

A representation captures the current state of a resource.

A representation is computed (“rendered”) when a resource isrequested (“late binding”).

Where?

I process data where it is located and send result to client,

I encapsulate data in an object and send object to client,

I send data and metadata so client can determine processing.

All may be employed by REST.

A representation is both data and metadata.

I representation data typically in XML;

I metadata typically in HTTP headers.

Henning Niss (ITU) REST Lecture 7 19 / 34

Page 18: Rest Overview

The REST architectural style

ConnectorsA connector is an abstract interface for network communication.

Key requirement: stateless.

I each request includes all necessary information to process it,

å no resources need be held,

å need no knowledge of interaction semantics with other requests,

å intermediaries may inspect communication in isolation.

Interface:

I in params: control data, resource id, optional resource repr,

I out params: control data, optional resource/repr metadata,optional resource repr.

Synchronous invocation, but may use streams for input and output.

Example connectors: client, server, cache.

Henning Niss (ITU) REST Lecture 7 20 / 34

Page 19: Rest Overview

The REST architectural style

Processing elements

Processing elements (components) “performs” requests andresponses.

Example processing elements: user agent and origin server.

I A user agent (uses a client connector)I sends requests and receives replies;I renders the result;I example: Web browser.

I An origin server (uses a server connector)I serves requested resources;I resource implementation details not revealed;I must be ultimate endpoint for updates.

Example: Proxies (acting as both clients and servers).

Henning Niss (ITU) REST Lecture 7 21 / 34

Page 20: Rest Overview

The REST architectural style

Architectural views

Views describe how the architectural elements works together.

I A process view shows how data flows through the system.

I A connector view shows how components communicate.

I A data view shows how the state of the system evolves.

Henning Niss (ITU) REST Lecture 7 22 / 34

Page 21: Rest Overview

The REST architectural style

Example view (process view)

Henning Niss (ITU) REST Lecture 7 23 / 34

Page 22: Rest Overview

Example: REST in the Joke server

Web of Jokes

Infrastructure for a world-wide network of servers and clients forauthoring, publishing, and reading jokes.

Henning Niss (ITU) REST Lecture 7 25 / 34

Page 23: Rest Overview

Example: REST in the Joke server

Operations

Joke server operations:

I list (joke categories);

I retrieve(category) (jokes of a specified category);

I submit() (joke in body of POST request).

Henning Niss (ITU) REST Lecture 7 26 / 34

Page 24: Rest Overview

Example: REST in the Joke server

Joke server (List)

public class List extends HttpServlet {public void doGet(HttpServletRequest req, HttpServletResponse resp)

throws IOException, ServletException{try {resp.setContentType("text/xml");Document doc = new Jokes(getServletContext()).getJokes();String xslt =getServletContext().getInitParameter("CategoriesXSLT");

XSLTransformer t = new XSLTransformer(xslt);new XMLOutputter().output(t.transform(doc), resp.getWriter());

} catch (Exception e) {resp.sendError(500, "Internal error");

} } }

Henning Niss (ITU) REST Lecture 7 27 / 34

Page 25: Rest Overview

Example: REST in the Joke server

Joke server (List stylesheet)

<xsl:stylesheet version="1.0"xmlns="http://www.brics.dk/ixwt/categories"xmlns:jml="http://www.brics.dk/ixwt/jokes"xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="jml:collection"><categories><xsl:apply-templates select=

"jml:joke[not(@category=following::jml:joke/@category)]"/></categories>

</xsl:template><xsl:template match="jml:joke"><category><xsl:value-of select="@category"/>

</category></xsl:template>

</xsl:stylesheet>

Henning Niss (ITU) REST Lecture 7 28 / 34

Page 26: Rest Overview

Example: REST in the Joke server

Joke server (Retrieve)

public class Retrieve extends HttpServlet {public void doGet(HttpServletRequest req, HttpServletResponse resp)

throws IOException, ServletException{try {resp.setContentType("text/xml");Document doc = new Jokes(getServletContext()).getJokes();Transformer t =TransformerFactory.newInstance().newTransformer(new StreamSource(new File(getServletContext().getInitParameter("RetrieveXSLT"))));

t.setParameter("category", req.getParameter("category"));t.transform(new JDOMSource(doc), new JDOMResult());new XMLOutputter().output(out.getDocument(), resp.getWriter());

} catch (Exception e) {resp.sendError(500, "Internal error");

} } }

Henning Niss (ITU) REST Lecture 7 29 / 34

Page 27: Rest Overview

Example: REST in the Joke server

Joke server (Submit)

public class Submit extends HttpServlet {static Namespace jml =

Namespace.getNamespace("http://www.brics.dk/ixwt/jokes");public void doPost(HttpServletRequest req, HttpServletResponse resp)

throws IOException, ServletException{PrintWriter out = resp.getWriter();SAXBuilder b = new SAXBuilder();// set schema validation properties ...try {Document doc = b.build(req.getInputStream());if (!doc.getRootElement().getNamespaceURI().equals(jml))resp.sendError(400, "Wrong namespace of root element!");

elsenew Jokes(getServletContext()).addJokes(doc);

} catch (Exception e) {resp.sendError(500, "Internal error");

} } }

Henning Niss (ITU) REST Lecture 7 30 / 34

Page 28: Rest Overview

Example: REST in the Joke server

Jokes database (I)public class Jokes {

static Namespace jml =Namespace.getNamespace("http://www.brics.dk/ixwt/jokes");

ServletContext context;String jokeFile;Document jokes;

public Jokes(ServletContext ctx) throws JDOMException, IOException {context = ctx;jokes = (Document)ctx.getAttribute("jokes");jokeFile = ctx.getInitParameter("JokeFile");if (jokes==null) {try {jokes = new SAXBuilder().build(new File(jokeFile));

} catch (Exception e) {jokes = new Document(new Element("collection", jml));

}ctx.setAttribute("jokes", jokes);

} }

Henning Niss (ITU) REST Lecture 7 31 / 34

Page 29: Rest Overview

Example: REST in the Joke server

Jokes database (II)

public Document getJokes() { return jokes; }

public void addJokes(Document m) throws JDOMException, IOException {synchronized(context) {

jokes.getRootElement().addContent(m.getRootElement().removeContent());

new XMLOutputter().output(jokes, new FileOutputStream(new File(jokeFile)));

}}

}

Henning Niss (ITU) REST Lecture 7 32 / 34

Page 30: Rest Overview

Example: REST in the Joke server

Summary

I resource-centric;

I resources are named (identified);

I representations rather than resources;

I based on standardized protocol (HTTP);

I focus on architecture rather than implementation detail.

Henning Niss (ITU) REST Lecture 7 33 / 34