This is a presentation which describe the big picture of the Rest API. In this presentation I simply describe the theories with practical examples. Hope this presentation will cover the overall Rest API domain.
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
Rest API
1. By Rohana K Amarakoon
1
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
2. Invented World Wide Web, HTML, Web Browser
Tim Berners-Lee
New Version Hypertext Transfer Protocol, (HTTP/1.1)
Formalize Uniform Resource Identifiers (URI)
Standards quickly spread across the Web and
paved the way for its continued growth.
Web Scalability
2
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
3. In year 2000 Roy Fielding named and described the Web’s architectural style
“Representational State Transfer” (REST).
REST
REST APIs
Web API (Application Programming Interface)
REST architectural style design of APIs for modern web services. A Web API conforming to
the REST architectural style is a REST API.
Face of web service
Directly listening & responding to client requests
3
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
5. Having a REST API
web service “RESTful”
consists of an assembly of interlinked resources.
Set of resources is known as the REST API’s resource model.
Well-designed REST APIs can attract client developers to use web services.
REST API Design
REST API design are implicit in the HTTP standard.
Design rules are drawn from the de facto standards.
Web Resource Modeling Language (WRML) – Rules in JSON format
(conceptual framework for resource model diagramming technique )
5
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
6. http://api.example.restapi.org/france/paris/louvre/leonardo-da-vinci/mona-lisa
Uniform Resource Identifiers (URI)
URI Formats
Good URI
Bad URI
http://api.example.restapi.org/68dd0-a9d3-11e0-9f1c-0800200c9a66
REST APIs use URIs to address resources.
The rules are in format of a URI. RFC 3986*
URI syntax example :
URI = scheme "://" authority "/" path [ "?" query ] [ "#" fragment ]
6
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
7. (/) separator indicate a hierarchical relationship
Hyphens (-) used to improve the readability URI
http://api.example.restapi.org/blogs/mark-masse/entries/this-is-my-first-post
Improve the readability of names in long path segments
http://api.canvas.restapi.org/shapes/polygons/quadrilaterals/squares
Tailing (/) should not be included in URIs
http://api.canvas.restapi.org/shapes/
http://api.canvas.restapi.org/shapes
7
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
8. Underscores (_) should not be used in URIs
http://api.example_restapi.org/blogs/mark-masse/entries/this-is-my-first-post
http://api.example_restapi.org/blogs/mark-masse/entries/this-is-my-first-post
(_) Partially obscured or completely hidden by this underlining.
Lowercase letters should be preferred in URI paths
RFC 3986 defines URIs are case-sensitive
http://api.example.restapi.org/my-folder/my-doc
HTTP://API.EXAMPLE.RESTAPI.ORG/my-folder/my-doc
http://api.example.restapi.org/My-Folder/my-doc
unnecessary confusion
8
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
9. File extensions should not be included in URIs
http://api.college.restapi.org/students/3248234/transcripts/2005/fall
http://api.college.restapi.org/students/3248234/transcripts/2005/fall.json
Consistent sub domain names for APIs
The top-level domain and then sub domain names.
http://api.soccer.restapi.org
URI Authority Design
Top level domain Sub domain
9
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
10. Consistent sub domain names for client developer Portal
The top-level domain and then sub domain names.
http://developer.soccer.restapi.org
URI Authority Design
Developer portal Sub domain
10
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
11. ( /) separated path segment corresponding to unique resource
http://api.soccer.restapi.org
http://api.soccer.restapi.org/leagues
http://api.soccer.restapi.org/leagues/seattle
http://api.soccer.restapi.org/leagues/seattle/teams
http://api.soccer.restapi.org/leagues/seattle/teams/trebuchet
Base Line
Bottom
Line
11
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
12. Document (Base Archetype)
Resource archetypes helps consistently communicate the structures and
behaviors.
http://api.soccer.restapi.org/leagues/seattle
http://api.soccer.restapi.org/leagues/seattle/teams/trebuchet
http://api.soccer.restapi.org/leagues/seattle/teams/trebuchet/players/mike
identifies a document resource
Collection
http://api.soccer.restapi.org/leagues
http://api.soccer.restapi.org/leagues/seattle/teams
http://api.soccer.restapi.org/leagues/seattle/teams/trebuchet/players
server-managed directory of resources
12
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
13. Store
PUT /users/1234/favorites/Alonso
client-managed resource repository
Controller
Controller names typically appear as the last segment in a URI path
POST /alerts/245743/resend
Executable functions, with parameters and return values; inputs and outputs
13
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
14. A singular noun for document names
http://api.soccer.restapi.org/leagues/seattle/teams/trebuchet/players/clau
dio
WRML diagram of a URI’s associated resource model
A plural noun collection names
http://api.soccer.restapi.org/leagues/seattle/teams/trebuchet/players
14
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
15. A plural noun for store names
http://api.music.restapi.org/artists/mikemassedotcom/playlists
A verb or verb phrase for controller names
http://api.college.restapi.org/students/morgan/register
Variable path segments substituted with identity-based Values
http://api.soccer.restapi.org/leagues/{leagueId}/teams/{teamId}/players/{playerId}
http://api.soccer.restapi.org/leagues/seattle/teams/trebuchet/players/21
CRUD function names should not be used in URIs
Preferred: DELETE /users/1234
What not to do: GET /deleteUser?id=1234
GET /deleteUser/1234
DELETE /deleteUser/1234
POST /users/1234/delete
15
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
16. Define a query
URI = scheme "://" authority "/" path [ "?" query ] [ "#" fragment ]
Query is an unique identification of a resource
http://api.college.restapi.org/students/morgan/send-sms
http://api.college.restapi.org/students/morgan/send-sms?text=hello
Query provide additional interaction capabilities
ad hoc searching
Filtering
16
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
17. Query component used to filter collections or stores
GET /users
GET /users?role=admin
Query component used to paginate collection or store results
Parameters : pageSize (maximum number of contained elements )
pageStartIndex (zero-based index of the first element )
GET /users?pageSize=25&pageStartIndex=50
17
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
18. Request methods
Request-Line = Method SP Request-URI SP HTTP-Version CRLF
Response codes
100 200 300 400
Message headers
REST API USE HTTP 1.1
18
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
19. Request methods
Request-Line = Method SP Request-URI SP HTTP-Version CRLF
GET /greeting HTTP/1.1
GET and POST must not be used to tunnel other request meth
Tunneling : misrepresents a message
undermines the protocol’s transparency
GET used to retrieve a representation of a resource
GET /greeting HTTP/1.1
Request Methods
19
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
20. HEAD used to retrieve response headers
Date: Sat, 20 Aug 2011 16:02:40 GMT
PUT used to insert and update a stored / mutable resource
PUT /accounts/4ef2d5d0-cb7e-11e0-9572-0200c9a66/buckets/objects/4321
POST used to create a new resource in a collection
Execute function oriented controllers
POST /leagues/seattle/teams/trebuchet/players
POST /alerts/245743/resend
20
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
21. DELETE used to remove a resource from its parent
DELETE /accounts/4ef2d5d0-cb7e-11e0-9572-800200c9a66/buckets/objects/4321
OPTIONS used to retrieve metadata describes a resource’s
available interactions
Allow: GET, PUT, DELETE
21
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
22. Term Description
DELETE HTTP request method (RM) - remove its parent.
GET HTTP RM - retrieve a representation of a resource’s state.
HEAD HTTP RM - retrieve the metadata associated with the resource’s
state.
OPTIONS HTTP RM - retrieve metadata that describes a resource’s available
interactions.
POST HTTP RM - create a new resource within a collection or execute a
controller.
PUT HTTP RM - insert a new resource into a store or update a mutable
resource.
22
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
24. Term Description
Request-Line RFC 2616 defines its syntax as :
Method SP Request-URI SP HTTP-Version CRLF
Request method Indicates the desired action to be performed on the request
message’s identified resource.
Response status 3-digit numeric value communicated by a server to indicate result
code of client’s request.
Status-Line RFC 2616 defines its syntax as:
HTTP-Version SP Status-Code SP Reason-Phrase CRLF
Tunneling An abuse of HTTP that masks or misrepresents a message’s intent
and undermines the protocol’s transparency.
24
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
25. Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
Response Status Codes Categories
Category Description
1xx: Informational Communicates transfer protocol-level information.
2xx: Success Indicates that the client’s request was accepted successfully.
3xx: Redirection Indicates that the client must take some additional
action in order to complete their request.
4xx: Client Error.
5xx: Server Error.
25
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
26. Response Status Codes In Detail
Code Name Meaning
200 OK Indicates a nonspecific success
201 Created Sent primarily by collections and stores
202 Accepted Sent by controllers to indicate the start of an
asynchronous action
204 No Content Indicates that the body has been
intentionally left blank
26
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
27. Code Name Meaning
301 Moved New permanent URI has been assigned to the
client’s requested resource
303 See Other Sent by controllers to return results that it considers
optional
304 Not Modified Sent to preserve bandwidth (with conditional GET)
307 Temporary Indicates that a temporary URI has been
Redirect assigned to the client’s requested resource
27
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
28. Code Name Meaning
400 Bad Request Indicates a nonspecific client error
401 Unauthorized Sent when the client either provided invalid
credentials or forgot to send them
402 Forbidden Sent to deny access to a protected resource
404 Not Found Sent when the client tried to interact with a URI
that the REST API could not map to a resource
405 Method Not Sent when the client tried to interact using an
Allowed unsupported HTTP method
28
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
29. Code Name Meaning
406 Not Acceptable Sent when the client tried to request data
in an unsupported media type format
409 Conflict Indicates that the client attempted to
violate resource state
412 Precondition Failed Tells the client that one of its preconditions
was not met
415 Unsupported Media Sent when the client submitted data
Type in an unsupported media type format
500 Internal Server Error Tells the client that the API is having
problems of its own
29
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
30. Various forms of metadata conveyed through the entity headers
HTTP’s request
HTTP’s response messages.
REST API HTTP’s standard headers
Content-Type - type of data (ex - media type)
Content-Length - size of the entity-body in bytes
Last-Modified - should be used in responses only
Etag – version in the response’s entity
30
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
31. Stores support conditional PUT requests
(insert and update)
client#1 PUT client#2
creates 200 Created
overwrite 409 Conflicts
update 412 Precondition Failed
update 200 Ok (match)
update 209 No Content
31
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
32. Cache-Control, Expires, and Date used to encourage caching
Date: Tue, 15 Nov 1994 08:12:31 GMT
Expires: Thu, 01 Dec 1994 16:00:00 GMT
Expiration caching headers
should be used with 200 (“OK”) responses
optionally be used with 3xx and 4xx responses
Custom HTTP headers must not be used to change the behavior of
HTTP methods
32
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
33. Media Type Syntax
type "/" subtype *( ";" parameter )
type
application audio image message
model multipart text video
parameters
follow the type/subtype in the form of attribute=value separated by
(;)
Parameter values case-sensitive and enclosed in (“ ”) characters.
Content-type: text/html; charset=ISO-8859-4
Content-type: text/plain; charset="us-ascii" 33
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
34. Registered Media Types
Governed by Internet Assigned Numbers Authority† (IANA)
text/plain
no specific content structure or markup.
text/html
Content that is formatted using the Hyper Text Markup Language
HTML).
image/jpeg
An image compression method that was standardized by the Joint
Photographic Experts Group (JPEG).‖
application/xml
Content that is structured using the Extensible Markup Language
(XML). 34
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
35. application/atom+xml
Content is XML-based format that structures data into lists known
as feeds.
application/javascript
Source code written in the JavaScript programming language.
application/json
The JavaScript Object Notation (JSON) text-based format often used
to exchange structured data.
Vendor-Specific Media Types
application/vnd.ms-excel
application/vnd.lotus-notes
text/vnd.sun.j2me.app-descriptor
35
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
36. Message Body Format
Commonly used XML and JSON formats
XML < > tag pairs.
JSON { } hierarchically structure.
XML – (EXtensible Markup Language)
XML and other formats may optionally be used for resource
representation
JSON – (JavaScript Object Notation)
supported for resource representation
must be well-formed
36
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
37. XML
XML is a markup language much like HTML
XML was designed to carry data, not to display data
XML tags are not predefined. You must define your own tags
XML is designed to be self-descriptive
XML is a W3C Recommendation
XML was created to structure, store, and transport information.
37
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
38. JSON
{
"firstName" : "Osvaldo",
"lastName" : "Alonso",
"firstNamePronunciation" : "ahs-VAHL-doe",
"number" : 6,
"birthDate" : "1985-11-11"
}
all names enclosed in “ “
supports number values directly
date-time values, typically formatted as strings
JSON is universally accepted as a ‘front-end’ language
38
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
40. consistent form should be used to represent links
WRML media type
application/wrml;
format=“http://api.formats.wrml.org/application/json”;
schema=“http://api.schemas.wrml.org/common/Link” Link , LinkRelation,
Format
JSON
{
"href" : Text <constrained by URI or URI Template syntax>,
"rel" : Text <constrained by URI syntax>,
"requestTypes" : Array <constrained to contain media type text elements>,
"responseTypes" : Array <constrained to contain media type text elements>,
"title" : Text
}
40
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
41. consistent form should be used to represent relations
WRML media type
application/wrml;
format=“http://api.formats.wrml.org/application/json”;
schema=“http://api.schemas.wrml.org/common/LinkRelation”
JSON
{
"name" : Text,
"method" : Text <constrained to be choice of HTTP method>,
"requestTypes" : Array <constrained to contain media type text elements>,
"responseTypes" : Array <constrained to contain media type text elements>,
"description" : Text,
"title" : Text
}
41
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
42. Links should be used to advertise a resource’s available actions in a
state-sensitive manner
{
# Fields...
"links" : {
“self" : {
"href" : "http://api.editor.restapi.org/docs/48679",
"rel" : "http://api.relations.wrml.org/common/self"
},
"cut" : {
"href" : "http://api.editor.restapi.org/docs/48679/edit/cut",
"rel" : "http://api.relations.wrml.org/editor/edit/cut"
},
"copy" : {
"href" : "http://api.editor.restapi.org/docs/48679/edit/copy",
"rel" : "http://api.relations.wrml.org/editor/edit/copy"
}
}
} 42
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
43. A consistent form used to represent media type formats
# Request
GET /application/json HTTP/1.1
Host: api.formats.wrml.org
# Response
HTTP/1.1 200 OK
Content-Type: application/wrml;
format="http://api.formats.wrml.org/application/json";
schema="http://api.schemas.wrml.org/common/Format"
{
"mediaType" : "application/json",
"links" : {
"self" : {
"href" : "http://api.formats.wrml.org/application/json",
"rel" : "http://api.relations.wrml.org/common/self"
},
"home" : {
"href" : "http://www.json.org",
"rel" : "http://api.relations.wrml.org/common/home"
Media Type Representation | 57
},
}
} 43
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
45. REST APIs are designed to suit the needs of their client programs
Why Versioning ????
REST API is a resource model (composed of an assembly of interlinked
resources)
Version form representation
state
format="http://api.formats.wrml.org/application/json";
schema="http://api.schemas.wrml.org/common/Format"
New URIs should be used to introduce new concepts
form and state change (maintain a consistent
mapping)
identifier must consistently address the same thought 45
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
46. Schemas used to manage representational form versions
REST API’s resource representations managed by versioned schema
documents
New schema
Adding fields and links new features (REST API)
Entity tags used to manage representational state versions
HTTP header : HTTP 1.1
46
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
47. Security
OAuth used to protect resources (Open Authorization / “open standard )
Web site #01 Share info Web site #2
Username & Password
OAuth - HTTP-based authorization protocol
OAuth – version 1.0 and 2.0 (Differences)
47
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
54. The query component of a URI should be used to support partial
responses
Save on bandwidth & accelerate the overall interaction, a REST API’s client
can use the query component to trim response data.
# Request
GET /students/morgan?fields=(firstName, birthDate) HTTP/1.1
Host: api.college.restapi.org
# Response
HTTP/1.1 200 OK
Content-Type: application/wrml;
format="http://api.formats.wrml.org/application/json";
schema="http://api.schemas.wrml.org/college/Student";
fields="(birthDate, firstName)"
{
"firstName" : "Morgan",
"birthDate" : "1992-07-31"
}
54
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
55. JavaScript facilitates applications that are instantly available
everywhere.
JS programs provide the interactive parts of web experiences.
JS make: applications dynamic, games playable, and advertisements
noticeable.
Web browsers enforce the same origin policy to prevent leaking of
confidential user data.
following resources have the same origin:
http://restapi.org
http://restapi.org:80 same : (default port)
http://restapi.org/js/my-mashup.js same : (specific file)
55
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
56. following resources has a different origin.
http://restapi.org
https://restapi.org
http://www.restapi.org
http://restapi.org:8080
https://restapi.org:80
http://restapi.com
http://wrml.org
56
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
57. JSONP supported to provide multi-origin read access from JavaScript
57
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
58. CORS provide multi-origin read/write access from JavaScript
58
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
59. REST API development frameworks originally created to help build
web applications
Developers don’t want to code web page templates to format their
REST API’s data
Built-in XML and JSON-based serialization and deserialization of the server’s
objects.
59
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
60. Current REST API development frameworks lack direct support for:
Uniform, cross-format hypermedia structures
Media type schema validation and versioning
Both partial and dynamically composed response bodies
Integration with client identification and entitlement authority
Multi-origin resource sharing with JSONP and CORS
60
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
61. For more information
E-mail :
Rohana.blogs@gmail.com
Blog :
http://uncopyrightables2011.blogspot.com/
Twitter :
@MaxRohana
Copyright to Rohana K Amarakoon @ http://uncopyrightables2011.blogspot.com/
61