DESIGNINGA RESTFUL WEB SERVICE
INTRODUCTION
XML over HTTPPretty URLs                REST ?      Any web service that’s not SOAP
THEORY• REpresentational   State Transfer• Defined   in 2000 by Roy Fielding in his doctoral dissertation ‘Architectural St...
RESOURCES• What   your web service is all about ≈ domain entities                     Order, Customer, ...• Nouns, not Ver...
BEHAVIORPOST = CreateGET = ReadPUT = Update ... and CreateDELETE = Delete
BEHAVIOR• Safe   = no side effects• Idempotent    = multiple requests same effect as single request                     GE...
REPRESENTATION• Client   and server exchange representations of a resource• HTTP       headers provide info about chosen r...
BASIC DESIGN1. IDENTIFYING RESOURCES2. CHOOSING REPRESENTATION3. RESPONSES4. HANDLING ERRORS
IDENTIFYING RESOURCES
IDENTIFYING RESOURCES                             Asset/assets                        /assets/{id}GET = retrieve all asset...
IDENTIFYING RESOURCES               Asset                                 Attachment                                      ...
IDENTIFYING RESOURCES              Asset                                 Attachment                                       ...
IDENTIFYING RESOURCES                            0 ... *                                                       links      ...
IDENTIFYING RESOURCES• We   only need two URIs: • one   for a collection resource • one   for an instance resource• Use-ca...
CHOOSING REPRESENTATION
CHOOSING REPRESENTATION• No    single format for all representations  • varying   application use cases and client needs• ...
CHOOSING REPRESENTATION• Sometimes     need for combination of textual and binary data  • e.g. XML   and image data• Possi...
CHOOSING REPRESENTATIONContent-Type: multipart/form-data; boundary=“abcd”--abcdContent-Type: application/xmlContent-Dispos...
CHOOSING REPRESENTATION• Media     type extensions • XML       based types end with +xml • for     vendor specific extensio...
RESPONSES
RESPONSESGET is obvious:    # Request    GET /assets/1234 HTTP/1.1    # Response    HTTP/1.1 200 OK    Content-Type: appli...
RESPONSESPOST not so obvious:    # Request    POST /assets HTTP/1.1    Content-Type: multipart/form-data; boundary=“abcd” ...
RESPONSESPUT for update:    # Request    PUT /assets/1234 HTTP/1.1    Content-Type: application/xml    <asset id=“1234”>  ...
RESPONSESDELETE   # Request   DELETE /assets/1234 HTTP/1.1   # Response   HTTP/1.1 204 No Content
HANDLING ERRORS
HANDLING ERRORS• Return    response with a 4xx status code for client errors• Indicate   server-side errors with a 5xx sta...
HANDLING ERRORS•   400 Bad Request    •   the request cannot be fulfilled due to bad syntax•   401 Unauthorized    •   auth...
HANDLING ERRORS•   500 Internal Server Error    •   best code to return when server fails due to some implementation bug• ...
ADVANCED DESIGN1. CONTENT NEGOTIATION2. QUERYING3. BASE WEB SERVICE URL4. SECURITY5. EXTENSIBILITY AND VERSIONING6. ASYNCH...
CONTENT NEGOTIATION
CONTENT NEGOTIATION• Let   client choose representation as much as possible• Different   mechanisms  • Accept-*   headers ...
CONTENT NEGOTIATION• Accept    for preferred media type(s)• Accept-Language         for preferred language(s)• Accept-Enco...
CONTENT NEGOTIATION     # Request headers     Accept: application/xml, application/json;q=0.5, */*;q=0.0     Accept-Langua...
CONTENT NEGOTIATION• Query   parameter like type, lang   GET /assets/1234?type=json&lang=fr HTTP/1.1• Resource   extension...
QUERYING
QUERYING• GET   on collection resource with query parameters  # Request  GET /assets?q=obama&sortbyAsc=createDate HTTP/1.1...
QUERYING• Pagination  # Request  GET /assets?q=obama&sortbyAsc=createDate&offset=50&limit=25 HTTP/1.1• Letting   clients d...
QUERYING• Storing   queries  # Request  POST /assets HTTP/1.1  Content-Type: application/x-www-form-urlencoded  q=obama&so...
BASE WEB SERVICE URL
BASE WEB SERVICE URL• Dedicated   URL• Same    URL for browser and REST client • only   different representations: HTML vs...
SECURITY
SECURITY• REST   is stateless so DON’T use HTTP sessions• Different   protocols  • Basic  • Oauth• Add   authentication fr...
EXTENSIBILITYAND VERSIONING
EXTENSIBILITY•   Preserve backwards compatibility !•   Use HTTP redirects    •   301 Moved Permanently        •   this and...
VERSIONING• Don’t   introduce a version unless you have breaking changes• URL: http://diocontentwebservice.persgroep.be/v2...
ASYNCHRONOUS TASKS
ASYNCHRONOUS TASKS• Creating   assets in dio:content is an asynchronous operation• Each   new asset is placed on a queue a...
ASYNCHRONOUS TASKS# Adding new assetPOST /assets HTTP/1.1Content-Type: multipart/form-data; boundary=“abcd”--abcdContent-T...
ASYNCHRONOUS TASKS# Checking status of check-inGET /checkins/1 HTTP/1.1# Processing assetHTTP/1.1 200 OKContent-Type: appl...
ASYNCHRONOUS TASKS# Canceling check-inDELETE /checkins/1 HTTP/1.1# check-in canceledHTTP/1.1 204 No Content# Already compl...
HATEOAS
HATEOAS        Hypermedia As The Engine Of Application State• Use   links to allow clients to discover locations and opera...
HATEOAS# RequestGET /assets?q=SELECT NAME FROM IMAGES WHERE FULLTEXT=‘obama’&limit=50 HTTP/1.1Accept: application/vnd.dioc...
HATEOAS# RequestGET /assets/1234 HTTP/1.1Accept: application/vnd.diocontent+xml# ResponseHTTP/1.1 200 OKContent-Type: appl...
HATEOAS# RequestGET /assets/1234/attachments HTTP/1.1Accept: application/vnd.diocontent+xml# ResponseHTTP/1.1 200 OKConten...
HATEOASWithout HATEOAS, your HTTP interface is not RESTful !
ENABLING DISCOVERY
ENABLING DISCOVERY• Please   document your REST API !  • describe   resources, methods, media types, authentication, ...  ...
THE END ... QUESTIONS ?
BOOKS ON REST•   Subbu Allamaraju RESTful Web Services Cookbook ISBN:    978-0596801687•   Leonard Richardson, Sam Ruby RE...
FURTHER READING•   RyanTomayko    How I Explained REST to my Wife    http://tomayko.com/writings/rest-to-my-wife•   Jim We...
Upcoming SlideShare
Loading in …5
×

Designing a RESTful web service

2,374
-1

Published on

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,374
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
47
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide
  • 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-&gt; dmv Content-Type kan server dit onderscheiden\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
  • Designing a RESTful web service

    1. 1. DESIGNINGA RESTFUL WEB SERVICE
    2. 2. INTRODUCTION
    3. 3. XML over HTTPPretty URLs REST ? Any web service that’s not SOAP
    4. 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. 5. RESOURCES• What your web service is all about ≈ domain entities Order, Customer, ...• Nouns, not Verbs• Identified by a URI
    6. 6. BEHAVIORPOST = CreateGET = ReadPUT = Update ... and CreateDELETE = Delete
    7. 7. BEHAVIOR• Safe = no side effects• Idempotent = multiple requests same effect as single request GET POST PUT DELETE SAFE Y N N NIDEMPOTENT Y N Y Y DON’T abuse GET for unsafe operations
    8. 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
    9. 9. BASIC DESIGN1. IDENTIFYING RESOURCES2. CHOOSING REPRESENTATION3. RESPONSES4. HANDLING ERRORS
    10. 10. IDENTIFYING RESOURCES
    11. 11. IDENTIFYING RESOURCES Asset/assets /assets/{id}GET = retrieve all assets GET = retrieve asset detailsPUT = update all assets PUT = update assetPOST = add a new asset POST = -DELETE = delete all assets DELETE = remove asset
    12. 12. IDENTIFYING RESOURCES Asset Attachment 0 ... */assets/{id}/attachmentsGET = retrieve all attachments of assetPUT = update all attachments of assetPOST = create a new attachmentDELETE = delete all attachments of asset
    13. 13. IDENTIFYING RESOURCES Asset Attachment 0 ... */assets/{id}/attachments/{role}GET = retrieve attachment with given rolePUT = replace or create attachment with given rolePOST = -DELETE = delete attachment with given role
    14. 14. IDENTIFYING RESOURCES 0 ... * links Asset 1/assets/{id}/links /assets/{id}/links/{id}GET = retrieve all links GET = check if link existsPUT = replace all links PUT = create linkPOST = add links POST = -DELETE = remove all links DELETE = remove link
    15. 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 ?
    16. 16. CHOOSING REPRESENTATION
    17. 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. 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
    19. 19. CHOOSING REPRESENTATIONContent-Type: multipart/form-data; boundary=“abcd”--abcdContent-Type: application/xmlContent-Disposition: form-data; name=asset<asset> <name>New asset</name> ...</asset>--abcdContent-Type: image/jpegContent-Disposition: form-data; name=binary; filename=newasset.jpg... image here ...--abcd
    20. 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 • ...
    21. 21. RESPONSES
    22. 22. RESPONSESGET is obvious: # Request GET /assets/1234 HTTP/1.1 # Response HTTP/1.1 200 OK Content-Type: application/xml <asset> <name>image.jpg</name> ... </asset>
    23. 23. RESPONSESPOST not so obvious: # Request POST /assets HTTP/1.1 Content-Type: multipart/form-data; boundary=“abcd” ... # Response HTTP/1.1 201 Created Location: http://diocontent.persgroep.be/assets/1234 Content-Type: application/xml <asset id=“1234”> <name>image.jpg</name> ... </asset>
    24. 24. RESPONSESPUT for update: # Request PUT /assets/1234 HTTP/1.1 Content-Type: application/xml <asset id=“1234”> <name>updated name</name> ... </asset> # Response HTTP/1.1 200 OK Content-Type: application/xml <asset id=“1234”> <name>updated name</name> ... </asset>
    25. 25. RESPONSESDELETE # Request DELETE /assets/1234 HTTP/1.1 # Response HTTP/1.1 204 No Content
    26. 26. HANDLING ERRORS
    27. 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. 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. 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. 30. ADVANCED DESIGN1. CONTENT NEGOTIATION2. QUERYING3. BASE WEB SERVICE URL4. SECURITY5. EXTENSIBILITY AND VERSIONING6. ASYNCHRONOUS TASKS7. HATEOAS8. ENABLING DISCOVERY
    31. 31. CONTENT NEGOTIATION
    32. 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. 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. 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. 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
    36. 36. QUERYING
    37. 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. 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. 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
    40. 40. BASE WEB SERVICE URL
    41. 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
    42. 42. SECURITY
    43. 43. SECURITY• REST is stateless so DON’T use HTTP sessions• Different protocols • Basic • Oauth• Add authentication from the start !
    44. 44. EXTENSIBILITYAND VERSIONING
    45. 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. 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
    47. 47. ASYNCHRONOUS TASKS
    48. 48. ASYNCHRONOUS TASKS• Creating assets in dio:content is an asynchronous operation• Each new asset is placed on a queue as a check-in
    49. 49. ASYNCHRONOUS TASKS# Adding new assetPOST /assets HTTP/1.1Content-Type: multipart/form-data; boundary=“abcd”--abcdContent-Type: application/xml...--abcdContent-Type: image/jpeg...--abcd# ResponseHTTP/1.1 202 AcceptedContent-Type: application/xmlContent-Location: http://diocontent.persgroep.be/checkins/1<checkIn id=“1”> <state>PENDING</state> <created>2012-02-01T18:20:10.000</created></checkIn>
    50. 50. ASYNCHRONOUS TASKS# Checking status of check-inGET /checkins/1 HTTP/1.1# Processing assetHTTP/1.1 200 OKContent-Type: application/xml<checkIn id=“1”> <state>PROCESSING</state> <created>2012-02-01T12:00:00.000</created> <processingStarted>2012-02-01T12:00:10.000</processingStarted></checkIn># Asset successfully addedHTTP/1.1 303 See OtherContent-Type: application/xmlLocation: http://diocontent.persgroep.be/assets/1234Content-Location: http://diocontent.persgroep.be/checkins/1<checkIn id=“1”> <state>DONE</state> <created>2012-02-01T18:20:10.000</created> <processingStarted>2012-02-01T12:00:10.000</processingStarted> <completed>2012-02-01T12:00:10.000</completed> <assetId>1234</assetId></checkIn>
    51. 51. ASYNCHRONOUS TASKS# Canceling check-inDELETE /checkins/1 HTTP/1.1# check-in canceledHTTP/1.1 204 No Content# Already completed check-in cannot be canceledHTTP/1.1 409 ConflictContent-Type: application/xml;charset=utf-8Location: http://diocontent.persgroep.be/assets/1234Content-Location: http://diocontent.persgroep.be/checkins/1<checkIn id=“1”> <state>DONE</state> <created>2012-02-01T18:20:10.000</created> <processingStarted>2012-02-01T12:00:10.000</processingStarted> <completed>2012-02-01T12:00:10.000</completed> <assetId>1234</assetId></checkIn>
    52. 52. HATEOAS
    53. 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 !
    54. 54. HATEOAS# RequestGET /assets?q=SELECT NAME FROM IMAGES WHERE FULLTEXT=‘obama’&limit=50 HTTP/1.1Accept: application/vnd.diocontent+xml# ResponseHTTP/1.1 200 OKContent-Type: application/vnd.diocontent+xml<?xml version=“1.0” encoding=“utf-8” ?><results xmlns=“http://diocontentapi.persgroep.be/schema/api” xmlns:atom=“http://www.w3.org/2005/Atom”> <assetResult> <attribute name="NAME">obama001.jpg</attribute> <atom:link rel=“self” href=“http://diocontent.persgroep.be/assets/1234”/> </assetResult> <assetResult> <attribute name="NAME">obama002.jpg</attribute> <atom:link rel=“self” href=“http://diocontent.persgroep.be/assets/4567”/> </assetResult> ... <atom:link rel=“first” href=“http://diocontent.persgroep.be/assets?q=...&offset=0&limit=50”/> <atom:link rel=“next” href=“http://diocontent.persgroep.be/assets?q=...&offset=50&limit=50”/> <atom:link rel=“last” href=“http://diocontent.persgroep.be/assets?q=...&offset=800&limit=50”/></results>
    55. 55. HATEOAS# RequestGET /assets/1234 HTTP/1.1Accept: application/vnd.diocontent+xml# ResponseHTTP/1.1 200 OKContent-Type: application/vnd.diocontent+xml<?xml version=“1.0” encoding=“utf-8” ?><asset id=“123” xmlns=“http://diocontentapi.persgroep.be/schema/api” xmlns:atom=“http://www.w3.org/2005/Atom”> <name>image.jpg</name> <createDate>2012-02-01T18:20:10.000</createDate> ... <atom:link rel=“self” href=“http://diocontent.persgroep.be/assets/1234”/> <atom:link rel=“alternate” href=“http://diocontent.persgroep.be/assets/1234” type=“image/jpeg”/> <atom:link rel=“related” href=“http://diocontent.persgroep.be/assets/1234/attachments”/> <atom:link rel=“related” href=“http://diocontent.persgroep.be/assets/1234/links”/></asset>
    56. 56. HATEOAS# RequestGET /assets/1234/attachments HTTP/1.1Accept: application/vnd.diocontent+xml# ResponseHTTP/1.1 200 OKContent-Type: application/vnd.diocontent+xml<?xml version=“1.0” encoding=“utf-8” ?><attachments id=“123” xmlns=“http://diocontentapi.persgroep.be/schema/api” xmlns:atom=“http://www.w3.org/2005/Atom”> <attachment> <role>original</role> ... <atom:link rel=“self” href=“http://diocontent.persgroep.be/assets/1234/attachments/original”/> <atom:link rel=“alternate” type=“image/jpeg” href=“http://diocontent.persgroep.be/assets/1234/attachments/original”/> </attachment> ... <atom:link rel=“self” href=“http://diocontent.persgroep.be/assets/1234/attachments”/> <atom:link rel=“related” href=“http://diocontent.persgroep.be/assets/1234”/></attachments>
    57. 57. HATEOASWithout HATEOAS, your HTTP interface is not RESTful !
    58. 58. ENABLING DISCOVERY
    59. 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
    60. 60. THE END ... QUESTIONS ?
    61. 61. BOOKS ON REST• Subbu Allamaraju RESTful Web Services Cookbook ISBN: 978-0596801687• Leonard Richardson, Sam Ruby RESTful Web Services ISBN: 978-0596529260
    62. 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

    ×