hypermedia apis
TRANSCRIPT
2ISEP/IPP
Building Hypermedia APIs with HTML5 andNode Mike Amundsen
ISBN: 978-1-4493-0657-1
RESTful web APIs Leonard Richardson, Mike Amundsen
ISBN: 1449358063
HYPERMEDIA API
3
“Programming for distributed hypermedia environments
usually means that message transfers must carry more than
just data; they must carry additional information including
metadata and higher-level application flow control
options.”Mike Amudsen 4
ISEP/IPP
RICHARDSON MATURITYMODEL
http://martinfowler.com/articles/richardsonMaturityModel.html
THE HYPERMEDIACONSTRAINT
Hipermedia as theengine of application
state *
* HATEOAS
HYPERMEDIA IS THE ENGINE
“hypermedia payloads carry more information than just the data
stored on the server. Hypermedia payloads carry two types of vital
metadata: metadata about the data itself and metadata about the
possible options for modifying the state of the application at that
moment.”Mike Amudsen
7ISEP/IPP
HYPERMEDIA API
Focus on
the media type and its hypermediacapabilities
not on
the API calls
9ISEP/IPP
H-FACTORS
Links represent opportunities for a
client to advance the state of the application by activating a link.
Controls provide support for additional
metadata when executing link operations.
Not all media typessupport all h-factors
11
ISEP/IPP
LINK H-FACTORS
H-Factor Example
LE Embed Links <img src=“…”>
LO Outbound Links
<a href=“…”>
LT TemplatedLinks
<form method="get" action=“…">
<input type="text" name="search" value="" />
<input type="submit" />
</form>
LI Idempotent Links
<link rel="edit" href=“…"/> (ATOM)
LN Non-Idempotent Links
<form method="post" action=“…">
<textarea name="comment"></textarea>
<input type="submit" />
</form>
12ISEP/IPP
CONTROL H-FACTORS
H-Factor Example
CR Read Controls Accept-Language: (http header)
CU Update Controls
<form method="post“ action=“…"
enctype="text/plain">
<textarea name="comment"></textarea>
<input type="submit" />
</form>
CM Method Controls
<form method="post“ action=“…">
<textarea name="comment"></textarea>
<input type="submit" />
</form>
CL Link Annotation Controls
<link rel="stylesheet" href="..." />
13ISEP/IPP
HYPERMEDIA MEDIA TYPE DESIGN
14
MEDIA TYPE
Describes the message structure and semantic
Use standard media types as much as possible http://www.iana.org/assignments/media-types/media-types.xhtml
Not all media types are hypermedia enabled, e.g., image/jpeg
15ISEP/IPP
EXAMPLE DATA (CSV)
darrel,admin,active
mike,manager,suspended
...
whartung,user,pending
16ISEP/IPP
EXAMPLE DATA WITHMETADATA
<ul class="users">
<li class="user">
<a href="..." rel="user">darrel</a>
<span class="role">admin</span>
<span class="status">active</span>
</li>
<li class="user">
<a href="..." rel="user">mike</a>
<span class="role">manager</span>
<span class="suspended">suspended</span>
</li>
...
</ul>
17ISEP/IPP
EXAMPLE APPLICATIONMETADATA
<ul class="users">
<li class="navigation"> <a href="..." rel="next-page">next-page</a>
</li>
<li class="navigation"> <a href="..." rel="last-page">last-page</a>
</li>
<li class="user"> ... </li>
...
</ul>
<!-- defined filters -->
<ul class="queries">
<li class="query"><a href="..." rel="admins">admins</a></li>
<li class="query"><a href="..." rel="pending">pending</a></li>
<li class="query"><a href="..." rel="suspended">suspended</a></li>
</ul>
<!-- user search -->
<form name="user-search" action="...">
<input name="search-name" value="" />
<input type="submit" />
</form>
18ISEP/IPP
HYPERMEDIA TYPE DESIGN ELEMENTS
Base Format
(client-initiated) State Transfer
Domain Style
Application Flow
19ISEP/IPP
BASE FORMAT
Plain text
CSV
JSON, XML,
HTML, Atom/AtomPub
…
20ISEP/IPP
(CLIENT INITIATED) STATE TRANSFER
None / read-only State is only transmitted from the server to the client
Predefined State transmitted from the client to the server follows predefined
payloads defined by the server and known by the client
Ad-hoc The server tells the client what state to trasmit. E.g., HTML <FORM>
21
ISEP/IPP
DOMAIN STYLE
Specific The payload has domain specific terms that are understood by client
and server, e.g., <shipping address>
General The payload uses some general blocks that can be reused in diferent
use cases, e.g., <adress type=“shipping”>
Agnostic The payload uses domain agnostic terms and (well known) decorators
to add semantic, e.g., <link rel=“edit”>
22
SPECIFIC DOMAIN STYLEEXAMPLE
<!-- domain-specific design -->
<order>
<id>...</id>
<shipping-address>...</shipping-address>
<billing-address>...</billing-address>
...
</order>
23ISEP/IPP
GENERAL DOMAIN STYLEEXAMPLE
/* domain-general design */
{
"order":
{
"id" : "...",
"address" :
{"type" : "shipping", "street-address" : "..."},
"address" :
{"type" : "billing", "street-address" : "..."}
}
}
24ISEP/IPP
AGNOSTIC DOMAIN STYLEEXAMPLE
<!-- domain-agnostic design -->
<ul class="order">
<li class="id">...</li>
<ul class="shipping-address">
<li class="street-address">...</li>
...
</ul>
<ul class="billing-address">
<li class="street-address">...</li>
...
</ul>
...
</ul>
25ISEP/IPP
APPLICATION FLOW
None The hypermedia type contains no identifiers for application flow.
Intrinsic The application flow identifiers are defined within the hypermedia
type itself. E.g., Atom and AtomPub define a small set of link relations to indicate application flow (“edit”, “edit-media”, and “self”).
Applied The application flow identifiers are not part of the hypermedia type,
but the type designs contain allowances (usually element decorators or attributes) for applying external values to indicate application flow. E.g., HTML attributes: profile, id, name, rel, and class.
26
NO APPLICATION FLOWEXAMPLE
Media type: text/uri-list
# urn:isbn:0-201-08372-8
http://www.huh.org/books/foo.html
http://www.huh.org/books/foo.pdf
ftp://ftp.foo.org/books/foo.txt
27ISEP/IPP
INTRINSIC APPLICATIONFLOW EXAMPLE
<!-- AtomPub -->
<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom">
<title>Atom-Powered Robots Run Amok</title>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<author><name>John Doe</name></author>
<content>Some text.</content>
<link rel="edit" href="http://example.org/edit/first-
post.atom"/>
</entry>
28ISEP/IPP
APPLIED APPLICATION FLOW EXAMPLE
<html><head>
<title>Payment Options</title><meta name="profile" content="http://www.example.com/profiles/payment.html" />
</head><body>
<h1>Payment Options</h1><p> <a href="..." rel="cancel-order">Cancel Order</a> </p><form href="..." name="credit-card" method="post">
<input name="card-number" value="" />...<input type="submit" />
</form><form href="..." name="purchase-order" method="post">
<input name="po-number" value="" />...<input type="submit" />
</form><form href="..." name="bank-draft" method="post">
<input name="routing-number" value="" />...<input type="submit" />
</form>...
</html>29
ISEP/IPP
AN EXAMPLE Message server
30
SIMPLE MESSAGE SERVICE
A service that allows users to post messages.
Post a new message
Update a message
Search messages by text, user, and date
Get all the messages of one user
Register a new user
Update the user data
Upload the user photo
31
ISEP/IPP
Message
User
1
0..n
MESSAGES RESOURCES
Resource The message collection
URL /message
GETPOSTPUTDELETE
return all messagescreate new entry, returns 201not allowednot allowed
Resource A message (Item in the collection)
URL /message/:id
GETPOSTPUTDELETE
return specific message or 404update existing entry or 404overwrite existing or create new given the iddeletes the message 32
ISEP/IPP
USERS RESOURCES
Resource The user collection
URL /user
GETPOSTPUTDELETE
return all userscreate new entry, returns 201not allowednot allowed
Resource An user
URL /user/:id
GETPOSTPUTDELETE
return specific user or 404updates existing entry or 404overwrite existing or create new given the iddeletes the user 33
ISEP/IPP
NO HYPERMEDIAREPRESENTATIONS
Message
{
id: "a1",
text: "Sample one",
sender: "Mary",
createdOn: now,
updatedOn: now
};
User
{
id: "Mary",
name:"Mary",
email: "[email protected]",
roles:[],
createdOn: now
};
34ISEP/IPP
Missing:• Explicit id as URI• Explicit links to other
resources• Application flow
HYPERMEDIA MISSING FOR MESSAGES
Message collection
Paging links First page
Next page
Previous page
Message Item
Resource links User
Message collection
Actions Edit the message
Delete the message
35ISEP/IPP
HYPERMEDIA MISSING FOR USERS
User collection
Paging links First page
Next page
Previous page
User Item
Resource links User’s messages
User’s photo
User collection
Actions Edit the user
Cancel user account
36ISEP/IPP
SOME DESIGN DECISIONS
Base format JSON
State transfer Predefined
Domain style Specific
Application flow Intrinsic
37ISEP/IPP
LINK RELATIONS
Don’t reinvent the weel
IANA http://www.iana.org/assignments/link-relations/link-relations.xhtml
Microformats http://microformats.org/wiki/existing-rel-values
38ISEP/IPP
COMMON LINK RELATIONS
rel Description Definition
collection
The target IRI points to a resource which represents the collection resource for the context IRI.
[RFC6573]
edit Refers to a resource that can be used to edit the link's context.
[RFC5023]
edit-form
The target IRI points to a resource where a submission form for editing associated resource can be obtained.
[RFC6861]
next Indicates that the link's context is a part of a series, and that the next in the series is the link target.
[HTML5]
payment
Indicates a resource where payment is accepted.
[RFC5988]
39
ISEP/IPP
Source: http://www.iana.org/assignments/link-relations/link-relations.xhtml
Message collection
{MESSAGE_KEY : { MESSAGE_REPRESENTATION
},…links: [
{ rel: "self", href: URI
},{ rel: "start", href: URI
},{ rel: "prev", href: URI
},{ rel: "next", href: URI
}]}
Message Item
{text: "Sample one",
createdOn: now, updatedOn: now,links: [{ rel: "self",href:
SERVER_ROOT+"/message/a1",},{ rel: "edit",href:
SERVER_ROOT+"/message/a1",},{ rel: "collection", href: SERVER_ROOT+"/message"
},{ rel: "psidi:user",href: SERVER_ROOT+"/user/Mary",
title: "Mary Smith"}
],};
User collection
{USER_KEY : { USER_REPRESENTATION },…links: [
{ rel: "self", href: URI
},{ rel: "start",
href: URI},{ rel: "prev",
href: URI},{ rel: "next",
href: URI}
]}
UserItem
{name:"Mary Smith", email:"[email protected]",
roles:[], createdOn: now, links: [{ rel: "self",
href: SERVER_ADDR+"/user/Mary",},{ rel: "edit",
href: SERVER_ADDR+"/user/Mary",},{ rel: "collection",
href: SERVER_ADDR+"/user"},{ rel: "psidi:user-messages",
href: SERVER_ADDR+"/message?user=Mary",
},{ rel: "psidi:user-photo",
href: SERVER_ADDR+"/user/Mary/photo",
},],};
{
"a11": {
"id": "a11",
"text": "Sample one",
"senderId": "Mary",
"createdOn": "2014-12-17T18:35:00.149Z",
"updatedOn": "2014-12-17T18:35:00.149Z",
"links": [
{
"rel": "self",
"href": "http://localhost:3001/message/a11"
},
{
"rel": "edit",
"href": "http://localhost:3001/message/a11"
},
{
"rel": "collection",
42ISEP/IPP
GET http://localhost:3001/messag
e
43ISEP/IPP
GET http://localhost:3001/message/a1
1
44ISEP/IPP
GET http://localhost:3001/user
45ISEP/IPP
GET http://localhost:3001/user/Mary
REPRESENTATION VS RESOURCE
Resource (e.g., table record)
{
id: PRIMARY_KEY
text: "Sample one",
senderId: FOREIGN_KEY TO
“users”
createdOn: now,
updatedOn: now,
};
Resource Representation{
text: "Sample one",
createdOn: now,
updatedOn: now,
links: [
{ rel: "self",
href: SERVER_ROOT+"/message/a1", // URI
},
{ rel: "edit",
href: SERVER_ROOT+"/message/a1", // URI
},
{ rel: "collection",
href: SERVER_ROOT+"/message“ // URI
},
{ rel: "psidi:user",
href: SERVER_ROOT+"/user/Mary", // URI
title: "Mary Smith“
}
],
};
46
CONTINUE THE ROAD TO HYPERMEDIA
Several things are missing:
Reuse generic collection media type, e.g., Collection+JSON, OData
Reuse existing media types and microformats, e.g., hCard
“New item” template
Search templates, e.g., OpenSearch
Photo subresource: information + media
47
ISEP/IPP
CLOSINGS
48
THE HYPERMEDIACONSTRAINT
“The application is therefore an engine that moves from one state to
the next by examining and choosing from among the
alternative state transitions in the current set of representations.”
Roy Fielding
49ISEP/IPP
SUGGESTED READINGS
Fielding, R. “REST APIs must be hypertext-driven”. http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
Atom/AtomPub. http://bitworking.org/projects/atom/rfc5023.html
Collection+JSON media type. http://amundsen.com/media-types/collection/
OData. http://www.odata.org/
OpenSearch. http://www.opensearch.org/Home
HTTP PATCH. http://tools.ietf.org/html/rfc5789
50ISEP/IPP