REST SERVICES AND JSON · REST Principles (1) • Addressable Resource: • The key abstraction of...
Transcript of REST SERVICES AND JSON · REST Principles (1) • Addressable Resource: • The key abstraction of...
REST SERVICES AND JSON
Sam Guinea [email protected] http://servicetechnologies.wordpress.com/
What is REST? • REST (Representational State Transfer)
• is a term coined by Roy Fielding in his Ph.D dissertation to describe an architecture style of networked systems.
• In it, he identifies specific architectural principles that answer the following questions: • Why is the Web so prevalent and ubiquitous? • What makes the Web scale? • How can I apply the architecture of the Web to my own
applications?
REST Principles (1) • Addressable Resource:
• The key abstraction of information and data in REST is a resource, and each resource must be addressable via a URI (Uniform Resource Identifier).
• A uniform, constrained interface: • Use a small set of well-defined methods to manipulate your
resources.
REST Principles (2) • Representation-oriented:
• You interact with services using representations of that service. • A resource referenced by one URI can have different formats. • Different platforms need different formats. For example, browsers
need HTML, JavaScript needs JSON (JavaScript Object Notation), and a Java application may need XML.
• Communicate statelessly: • Stateless applications are easier to scale.
• Hypermedia As The Engine Of Application State (HATEOS): • Let your data formats drive state transitions in your applications.
1. Addressable Resources • Addressability is the idea that every object and resource
in your system is reachable through a unique identifier.
• In the REST world, addressability is managed through the use of URIs. • Each HTTP request must contain the URI of the object you are:
• requesting information from • or posting information to.
• The format of URI is standardized as follows: scheme://host:port/path?queryString#fragment
• Example: http://example.com/customers?lastName=Burke&zipcode=02115
2. The Uniform, Constrained Interface • GET:
• read-only operation. • idempotent:
• no matter how many times you apply it, the result is always the same. • safe:
• its invocation does not change the state of the service. • PUT:
• like a resource upload • DELETE:
• remove resources. • POST:
• the only non-idempotent and unsafe operation. • is allowed to modify the service in a unique way.
• HEAD: • HEAD is like GET except it returns only a response code.
• OPTIONS: • is used to request information about the communication options of the resource. • It allows the client to determine the capabilities of a server and a resource without triggering actions
Uniform Interface
Why Is the Uniform Interface Important? • Familiarity:
• If you have a URI that points to a service, you know exactly which methods are available on that resource.
• Interoperability: • HTTP is a very ubiquitous protocol.
• Scalability: • HTTP caching increases the service performance. • With PUT and DELETE neither the client nor the server has to
worry about handling duplicate message delivery.
3. Representation-Oriented • Representations are exchanged between the client and
the service. • With a GET, you are receiving a representation of the current state
of the resource. • A PUT or POST passes a representation of the resource to the
server so that the underlying resource’s state can change.
• The representation is the message body of the request or response.
4. Communicate Statelessly • In REST, stateless means that there is no client session
data stored on the server.
• The server only records and manages the state of the resource it exposes.
• If needed, session-specific data: • should be held and maintained by the client. • transferred to the server with each request.
HATEOAS • Each resource representations contains hyperlinks. • Following a hyperlink takes the client to the next state.
• The resource representations themselves contain pointer to the next states.
An Example
• Parts Warehouse has some web services to enable its customers to: • get a list of parts • get detailed information about a particular part • submit a Purchase Order (PO)
SOAP Version
REST Way
A service to Get a list of parts • The web service makes available a URL to a parts list
resource
• A client uses this URL to get the parts list • http://www.warehouse.com/parts • How the web service generates the parts list is completely
transparent to the client. This is loose coupling.
• The web service may wish to allow the client to specify whether he/she wants the parts list as an HTML document, or as an XML document (representation)
Returned parts list
<?xml version="1.0"?> <p:Parts xmlns:p="http://www.parts-depot.com" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://www.parts-depot.com http://www.parts-depot.com/parts.xsd"> <Part id="00345" xlink:href="http://www.warehouse.com/parts/00345"/> <Part id="00346" xlink:href="http://www.warehouse.com/parts/00346"/> <Part id="00347" xlink:href="http://www.warehouse.com/parts/00347"/> <Part id="00348" xlink:href="http://www.warehouse.com/parts/00348"/> </p:Parts>
Get Detailed Information
• Service about a particular part
• The web service makes available a URL to each part resource
• This is how a client requests a specific part • http://www.warehouse.com/parts/00345?flavor=xml
Question
• Warehouse may have a million parts, will there be a million static pages? • We need to distinguish between a logical and a physical URL
• They express what resource is desired • They do not identify a physical object • The advantage of using logical URLs is that changes to the
underlying implementation of the resource will be transparent to clients
Complex Queries • For complex queries Warehouse will provide a service
(resource) for a client to retrieve a form that the client then fills in
• When the client submits the form • The browser will gather up the client’s responses and generate a
URL based on the responses • Oftentimes the client does not generate the URL (think about using
Amazon - you start by entering the URL to amazon.com; from then on you simply fill in forms, and the URLs are automatically created for you)
Submit a Purchase Order • The web service makes available a URL to submit a PO • The client creates a PO instance • The client submits PO.xml as the payload of an HTTP
POST
Submit PO Service (cont.) • The PO service responds to the HTTP POST with a URL
to the submitted PO • The client can retrieve the PO any time thereafter • The PO has become a piece of information which is shared
between the client and the server. The shared information (PO) is given an address (URL) by the server and is exposed as usual
Design Principles • Create a resource for every service
• Uniquely identify each resource with a logical URL
• Design your information to link to other information
• Web components (firewalls, routers, caches) make their decisions based upon information in the HTTP Header • The destination URL must be placed in the HTTP header for Web
components to operate effectively • It is anti-REST if the HTTP header just identifies an intermediate
destination and the payload identifies the final destination
WS vs REST • Message format
• REST: XML • SOAP: XML inside a SOAP envelope
• Interface definition • REST: none • SOAP: WSDL
• Transport • REST: HTTP • SOAP: HTTP, SMTP, FTP, JMS, etc
WS vs REST • SOAP encourages an RPC or message- oriented
architecture • Use HTTP as a transport (tunneling) • Single endpoint, many custom methods • Expose resources not “on the Web”
• REST puts the web back into web services • Based on Web architecture • Resources are “on the web” • Few methods (CRUD) but many resources • Take advantage of the web infrastructure
SOAP weaknesses • High perceived complexity
• Lack of architectural coherence
• Fragmentation
• Feature Bloat (Merge of competing specs)
• Lack of reference implementations
• Standardization of standards (WS-I)
SOAP strengths • SOAP/WSDL is the gateway technology to enable
interoperability • They work both over HTTP and other protocols
• Legacy reuse and integration • Pre-existing systems are not built to be Web-friendly • They use non-HTTP protocols
• Flexibility and adaptation • The same interface can be easily bound to different protocols as
business and technological requirements change
REST weaknesses • Confusion
• Mapping REST-style synchronous semantics on top of back end systems creates design mismatches
• Cannot go beyond HTTP/SSL
• Challenging to identify and locate resources appropriately in all applications • Semantics/Syntax description very informal (user/human oriented)
REST strengths • Simplicity
• Uniform interface is immutable • HTTP is ubiquitous (goes through firewalls) • Stateless/Synchronous interactions
• Proven scalability • “after all the Web works”
• Perceived ease of adoption (light infrastructure) • just need a browser to get started
• Leveraged by all major Web 2.0 applications • 85% clients prefer Amazon RESTful API
JSON
JSON • JavaScript Object Notation is a lightweight data-interchange
format. • Easy for humans to read and write. • Easy for machines to parse and generate. • The Fat-Free Alternative to XML • Very Common data-interchange format for REST. • Advantages:
• Language Independent • Simplicity • Interoperability • Openness
Main Features • JSON is built on two structures:
• A collection of name/value pairs. • In various languages, this is realized as an object, record, struct,
dictionary, hash table, keyed list, or associative array. • An ordered list of values. In most languages, this is realized as an
array, vector, list, or sequence.
• These are universal data structures. • Virtually all modern programming languages support them
in one form or another. • It makes sense that a data format that is interchangeable
with programming languages also be based on these structures.
Object • An object is an unordered set of name/value pairs.
Array • An array is an ordered collection of values separated by
comma.
Value • A value can be a string in double quotes, or a number, or
true or false or null, or an object or an array. • These structures can be nested.
String • A string is a sequence of zero or more Unicode
characters, wrapped in double quotes, using backslash escapes.
Number
Example JSON
{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}
Example XML
<menu id="file" value="File"> <popup> <menuitem value="New" onclick="CreateNewDoc()" /> <menuitem value="Open" onclick="OpenDoc()" /> <menuitem value="Close" onclick="CloseDoc()" /> </popup> </menu>