4. THEORY
• REpresentational State Transfer
• Defined in 2000 by Roy Fielding in his doctoral dissertation
‘Architectural Styles and the Design of Network-based Software
Architectures’
• Architectural style for network-based software applications
• not a protocol, unlike SOAP
• implementations use standards like HTTP, URI, XML, etc
5. RESOURCES
• What your web service is all about ≈ domain entities
Order, Customer, ...
• Nouns, not Verbs
• Identified by a URI
7. BEHAVIOR
• Safe = no side effects
• Idempotent = multiple requests same effect as single request
GET POST PUT DELETE
SAFE Y N N N
IDEMPOTENT Y N Y Y
DON’T abuse GET for unsafe operations
8. REPRESENTATION
• Client and server exchange representations of a resource
• HTTP headers provide info about chosen representation
• Content-Type: media type of representation
• Content-Length: size of representation in bytes
• Content-Encoding: for compressing representations
• Content-Language: for localized representations
11. IDENTIFYING RESOURCES
Asset
/assets /assets/{id}
GET = retrieve all assets GET = retrieve asset details
PUT = update all assets PUT = update asset
POST = add a new asset POST = -
DELETE = delete all assets DELETE = remove asset
12. IDENTIFYING RESOURCES
Asset Attachment
0 ... *
/assets/{id}/attachments
GET = retrieve all attachments of asset
PUT = update all attachments of asset
POST = create a new attachment
DELETE = delete all attachments of asset
13. IDENTIFYING RESOURCES
Asset Attachment
0 ... *
/assets/{id}/attachments/{role}
GET = retrieve attachment with given role
PUT = replace or create attachment with given role
POST = -
DELETE = delete attachment with given role
14. IDENTIFYING RESOURCES
0 ... *
links
Asset
1
/assets/{id}/links /assets/{id}/links/{id}
GET = retrieve all links GET = check if link exists
PUT = replace all links PUT = create link
POST = add links POST = -
DELETE = remove all links DELETE = remove link
15. IDENTIFYING RESOURCES
• We only need two URIs:
• one for a collection resource
• one for an instance resource
• Use-case scalability
• which resources will be added in the future ?
17. CHOOSING REPRESENTATION
• No single format for all representations
• varying application use cases and client needs
• XML (application/xml) and JSON (application/json) most
used
• Alternative formats for special cases
• image/jpeg, image/png, application/pdf,
application/vnd.ms-excel, text/plain, text/csv, ...
18. CHOOSING REPRESENTATION
• Sometimes need for combination of textual and binary data
• e.g. XML and image data
• Possible with multipart media types
• multipart/form-data most used
• Content-Disposition header for giving extra info
• DON’T encode binary data using Base64 encoding
20. CHOOSING REPRESENTATION
• Media type extensions
• XML based types end with +xml
• for vendor specific extensions the subtype starts with vnd.
• Examples
• application/atom+xml
• application/vnd.google-earth.kml+xml
• application/vnd.diocontent+xml
• ...
27. HANDLING ERRORS
• Return response with a 4xx status code for client errors
• Indicate server-side errors with a 5xx status code
• DON’T use a success status code, i.e. 2xx
• Include message in body with more information
DON’T DO
HTTP/1.1 200 OK HTTP/1.1 404 Not Found
Content-Type: application/xml Content-Type: application/xml
<error> <error>
Asset ‘1234’ not found Asset ‘1234’ not found
</error> </error>
28. HANDLING ERRORS
• 400 Bad Request
• the request cannot be fulfilled due to bad syntax
• 401 Unauthorized
• authentication is required but has failed or has not yet been provided
• 403 Forbidden
• request was valid but server is refusing to respond to it
• 404 Not Found
• requested resource could not be found but may be available again in the future
• 405 Method Not Allowed
• request was made using a method not supported by the resource
• 406 Not Acceptable
• cannot generate representation indicated by Accept headers of request
• 409 Conflict
• request could not be processed because of conflict in the request
29. HANDLING ERRORS
• 500 Internal Server Error
• best code to return when server fails due to some implementation bug
• 503 Service Unavailable
• the server is currently unavailable (because it is overloaded or down for
maintenance). Generally, this is a temporary state
30. ADVANCED DESIGN
1. CONTENT NEGOTIATION
2. QUERYING
3. BASE WEB SERVICE URL
4. SECURITY
5. EXTENSIBILITY AND VERSIONING
6. ASYNCHRONOUS TASKS
7. HATEOAS
8. ENABLING DISCOVERY
32. CONTENT NEGOTIATION
• Let client choose representation as much as possible
• Different mechanisms
• Accept-* headers
• query parameters
• extensions
• Use response code 406 (Not Acceptable) for failures
33. CONTENT NEGOTIATION
• Accept for preferred media type(s)
• Accept-Language for preferred language(s)
• Accept-Encoding when client can handle (de)compre
•q parameter indicates relative preference
• floating-point number in a range of 0.0 to 1.0 (default)
34. CONTENT NEGOTIATION
# Request headers
Accept: application/xml, application/json;q=0.5, */*;q=0.0
Accept-Language: nl, en-gb;q=0.8, en;q=0.7, *;q=0.1
Accept-Encoding: gzip
• XML is preferred media type, JSON is second choice, anything
else not acceptable
• ‘nl’ first choice, ‘en-gb’ second, ‘en’ third choice
• gzip compression is supported
35. CONTENT NEGOTIATION
• Query parameter like type, lang
GET /assets/1234?type=json&lang=fr HTTP/1.1
• Resource extension
GET /assets/1234.json HTTP/1.1
• Conventionally override Accept header
37. QUERYING
• GET on collection resource with query parameters
# Request
GET /assets?q=obama&sortbyAsc=createDate HTTP/1.1
# Response
HTTP/1.1 200 OK
Content-Type: application/xml
<assets>
<asset id=“1234”>...</asset>
<asset id=“4567”>...</asset>
...
</assets>
• POST for large queries exceeding maximum length of URI
# Request
POST /assets HTTP/1.1
Content-Type: application/x-www-form-urlencoded
q=obama&sortbyAsc=createDate
38. QUERYING
• Pagination
# Request
GET /assets?q=obama&sortbyAsc=createDate&offset=50&limit=25 HTTP/1.1
• Letting clients decide what they want
# Request
GET /assets?q=SELECT NAME FROM IMAGES WHERE FULLTEXT='obama'
# Response
HTTP/1.1 200 OK
Content-Type: application/xml
<results>
<assetResult>
<attribute name="NAME">obama001.jpg</attribute>
</assetResult>
<assetResult>
<attribute name="NAME">obama002.jpg</attribute>
</assetResult>
...
</results>
39. QUERYING
• Storing queries
# Request
POST /assets HTTP/1.1
Content-Type: application/x-www-form-urlencoded
q=obama&sortbyAsc=createDate
# Response
HTTP/1.1 201 Created
Content-Type: application/xml
Location: http://diocontent.persgroep.be/searches/1
# Use the created resource to fetch query results
GET /searches/1 HTTP/1.1
# Response
HTTP/1.1 200 OK
Content-Type: application/xml
<assets>
...
</assets>
# ... and with pagination
GET /searches/1?offset=50&limit=25 HTTP/1.1
41. BASE WEB SERVICE URL
• Dedicated URL
• Same URL for browser and REST client
• only different representations: HTML vs XML/JSON
http://diocontent.persgroep.be
vs.
http://diocontentwebservice.persgroep.be
45. EXTENSIBILITY
• Preserve backwards compatibility !
• Use HTTP redirects
• 301 Moved Permanently
• this and all future requests should be directed to the given URI
• 304 Temporary Redirect
• request should be repeated with another URI, using same method
• 410 Gone
• when resource used to exist, but it does not anymore
46. VERSIONING
• Don’t introduce a version unless you have breaking changes
• URL: http://diocontentwebservice.persgroep.be/v2
• Media type: application/vnd.diocontent+xml;v=2
53. HATEOAS
Hypermedia As The Engine Of Application State
• Use links to allow clients to discover locations and operations
• Clients do not need to known URLs, so they can change
• The entire application workflow is abstracted, thus changeable
• The hypermedia type itself could be versioned if necessary
• No breaking of clients if the implementation is updated !
59. ENABLING DISCOVERY
• Please document your REST API !
• describe resources, methods, media types, authentication, ...
• provide XML schema’s when using XML representations
• http://diocontentwebservice.persgroep.be
• Implement OPTIONS method to list supported methods
# Request
OPTIONS /asset/1234 HTTP/1.1
# Response
HTTP/1.1 204 No Content
Allow: GET, PUT, DELETE, HEAD, OPTIONS
61. BOOKS ON REST
• Subbu Allamaraju RESTful Web Services Cookbook ISBN:
978-0596801687
• Leonard Richardson, Sam Ruby RESTful Web Services ISBN:
978-0596529260
62. FURTHER READING
• RyanTomayko
How I Explained REST to my Wife
http://tomayko.com/writings/rest-to-my-wife
• Jim Webber, Savas Parastatidis & Ian Robinson
How to GET a Cup of Coffee
http://www.infoq.com/articles/webber-rest-workflow
• Roy Thomas Fielding
Architectural Styles and the Design of Network-based Software
Architectures
http://www.ics.uci.edu/~fielding/pubs/disser tation/top.htm
Hinweis der Redaktion
Als voorbeeld gebruiken we dio:content\n
\n
\n
\n
hoe URI ontworpen worden is heel belangrijk en daar gaan we veel aandacht aan besteden\n
\n
\n
resource is abstract, representation is iets heel concreet\n\nContent-Type zegt hoe ontvanger data moet interpreteren of parsen\n\n
Als voorbeeld gebruiken we dio:content\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
POST op zelfde URI als die om nieuw asset resource te maken\n-> dmv Content-Type kan server dit onderscheiden\n