Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

So you think you know REST - DPC11

1,955 views

Published on

These are the slides from the "So you think you know REST" talk at the Dutch PHP conference 2011. Plus some bonus slides I didn't have time for.

Published in: Technology
  • Be the first to comment

So you think you know REST - DPC11

  1. 1. So you think you know REST? <ul><li>An introduction to RESTful webservices, HTTP and best practices. </li></ul>
  2. 2. Evert Pot <ul><li>Engineer @ ibuildings
  3. 3. Interested in Web infrastructure, api design and scalability.
  4. 4. Runs the 'SabreDAV' open-source project. </li></ul>
  5. 5. The talk <ul><li>Short REST introduction
  6. 6. HTTP protocol basics
  7. 7. Advanced HTTP features </li></ul>
  8. 8. Defining REST
  9. 9. Defining REST <ul><li>Coined by Roy Fielding in 2000
  10. 10. Fielding is one of the HTTP 1.0 and 1.1 authors
  11. 11. Fielding's dissertation barely mentions HTTP </li></ul>
  12. 12. Defining REST <ul><li>Amazon S3 api
  13. 13. AtomPub
  14. 14. G(oogle)Data </li></ul>
  15. 15. Defining REST <ul><li>REST is an architectural style
  16. 16. Open to interpretation and discussion
  17. 17. Which is not what we're going to do </li></ul>
  18. 18. So you think you know REST
  19. 19. So you think you know REST
  20. 20. Designing proper RESTful services in an HTTP context while respecting the HTTP protocol design, where it makes sense.
  21. 21. REST vs. RPC
  22. 22. REST vs. RPC POST /api/?method=editPost&postId=123 POST /api/?method=getPost&postId=123 POST /1/statuses/update.json
  23. 23. REST vs. RPC POST /rpc HTTP/1.1 Host: www.example.org Content-Type: text/xml; charset=utf-8 <?xml version=”1.0”?> <methodCall> <methodName>getPhotos</methodName> <params> <param> <value><string>latest</string></value> </param> <param> <value><int>100</int></value> </param> </params> </methodCall>
  24. 24. REST vs. RPC HTTP/1.1 200 Ok Content-Type: text/xml; charset=utf-8 <?xml version=”1.0”?> <methodResponse> <params> <param> <value> <array> <data> <value><string>photo1.png</string></value> </data> </array> </value> </param> </params> </methodResponse>
  25. 25. REST vs. RPC POST /api/?method=getPosts&format=json POST /api/?method=getPost&postId=123&format=json POST /api/?method=newPost POST /api/?method=editPost&postId=123 POST /api/?method=deletePost&postId=123 POST /api/?method=publishPost&postId=123
  26. 26. REST vs. RPC POST /api/posts/index.json POST /api/posts/view/123.json POST /api/posts/add POST /api/posts/edit/123 POST /api/posts/delete/123 POST /api/posts/publish/123
  27. 27. REST vs. RPC GET /api/posts GET /api/posts/123 POST /api/posts PUT /api/posts/123 DELETE /api/posts/123
  28. 28. Representation GET /api/posts/123 HTTP/1.1 HTTP/1.1 200 Ok Content-Type: application/json { article : { title : “hello world”, body : “...” } }
  29. 29. Representation PUT /api/posts/123 HTTP/1.1 Content-Type: application/json { article : { title : “hello world, v2”, body : “...” } } HTTP/1.1 204 No Content
  30. 30. State Current database state Representation JSON or XML document Transfer GET, PUT, etc. Representational State Transfer
  31. 31. Benefits of RPC <ul><li>A lot of tooling available (SOAP)
  32. 32. An RPC API might map better to your existing (internal) api's.
  33. 33. Easily maps to popular programming languages. </li></ul>
  34. 34. Benefits of RESTful design <ul><li>Major components are well-defined and lots or prior art: </li><ul><li>Caching
  35. 35. Authentication
  36. 36. Proxies
  37. 37. Redirection
  38. 38. Addressability
  39. 39. Content-negotation
  40. 40. And so on.. </li></ul></ul>
  41. 41. HTTP!
  42. 42. HTTP Request PUT /articles/helloworld HTTP/1.1 Host: blog.example.org Content-Type: text/html Content-Length: 40 User-Agent: Hal/9000 <h1>Hello world</h1> ...
  43. 43. HTTP Response HTTP/1.1 415 Unsupported Media Type Content-Type: application/xml Content-Length: 576 Server: GeorgeForeman/2000 Date: Thu, 18 Nov 2010 16:40:04 GMT <?xml version=”1.0”?> <error> <message>You must submit articles in text/plain format</message> </error>
  44. 44. HTTP methods CONNECT DELETE GET HEAD OPTIONS POST PUT TRACE
  45. 45. HTTP methods ACL LABEL OPTIONS TRACE BASELINE-CONTROL LINK ORDERPATCH UNBIND BIND LOCK PATCH UNCHECKOUT CHECKIN MERGE POST UNLINK CHECKOUT MKACTIVITY PROPFIND UNLOCK CONNECT MKCALENDAR PROPPATCH UPDATE COPY MKCOL PUT UPDATEREDIRECTREF DELETE MKREDIRECTREF REBIND VERSION-CONTROL GET MKWORKSPACE REPORT HEAD MOVE SEARCH
  46. 46. HTTP methods ACL LABEL OPTIONS TRACE BASELINE-CONTROL LINK ORDERPATCH UNBIND BIND LOCK PATCH UNCHECKOUT CHECKIN MERGE POST UNLINK CHECKOUT MKACTIVITY PROPFIND UNLOCK CONNECT MKCALENDAR PROPPATCH UPDATE COPY MKCOL PUT UPDATEREDIRECTREF DELETE MKREDIRECTREF REBIND VERSION-CONTROL GET MKWORKSPACE REPORT HEAD MOVE SEARCH
  47. 47. HTTP GET <ul><li>Retrieval
  48. 48. Safe
  49. 49. No side-effects
  50. 50. Idempotent
  51. 51. Will return “200 Ok” in most cases </li></ul>
  52. 52. HTTP HEAD <ul><li>HEAD = GET – response body
  53. 53. Safe
  54. 54. No side-effects
  55. 55. Idempotent </li></ul>
  56. 56. HTTP PUT <ul><li>Update or create new resource at specified url
  57. 57. Not safe
  58. 58. Idempotent
  59. 59. Atomic
  60. 60. Return “200 Ok” or “201 Created” </li></ul>
  61. 61. HTTP DELETE <ul><li>Deletes a resource
  62. 62. Not safe
  63. 63. Idempotent
  64. 64. Atomic
  65. 65. Return “204 No Content” </li></ul>
  66. 66. HTTP POST <ul><li>Not safe
  67. 67. Not Idempotent
  68. 68. Used for RPC and 'everything else'
  69. 69. Most REST services use this to create new resources </li></ul>
  70. 70. Why POST for creation? PUT /articles HTTP/1.1 Content-Type: text/plain ..new article..
  71. 71. Why POST for creation? PUT /articles HTTP/1.1 Content-Type: text/plain ..new article.. <ul><li>Implies we're replacing /articles
  72. 72. Not idempotent </li></ul>
  73. 73. Except PUT /images/logo.png HTTP/1.1 Content-Type: image/png PUT /posts/550e8400-e29b-41d4-a716-446655440000 HTTP/1.1 Content-Type: application/json
  74. 74. HTTP PATCH <ul><li>Brand new (march 2010)
  75. 75. Used for partial updates, appending, etc.
  76. 76. Format is up to you
  77. 77. Not safe
  78. 78. Not idempotent
  79. 79. Not very RESTful </li></ul>
  80. 80. RESTful principals <ul><li>Strive for them
  81. 81. Don't religiously follow them </li></ul>
  82. 82. RESTful principals <ul><li>Strive for them
  83. 83. Don't religiously follow them
  84. 84. Start with a fully RESTful service
  85. 85. And then add workarounds and optimizations. </li></ul>
  86. 86. Responses Use appropriate HTTP status codes. Use the response body for additional about errors.
  87. 87. 1xx Informational 100 Continue 101 Switching Protocols 102 Processing
  88. 88. 2xx Success 200 Ok 201 Created 202 Accepted 203 Non-Authorative Information 204 No Content 205 Partial Content 207 Multi-Status 208 Already Reported 226 IM Used
  89. 89. 3xx Redirection 300 Multiple Choices 301 Moved Permanently 302 Found 303 See Other 304 Not Modified 305 Use Proxy 307 Temporary Redirect
  90. 90. 4xx Your Fault 400 Bad Request 401 Unauthorized 402 Payment Required 403 Forbidden 404 Not Found 405 Method Not Allowed 407 Proxy Authentication Required 408 Request Timeout 409 Conflict 410 Gone 411 Length Required 412 Precondition Failed 413 Request Entity Too Long 414 Request-URI Too Long 415 Unsupported Media Type 416 Requested Range Not Satisfiable 417 Expectation Failed 418 I'm a Teapot 422 Unprocessable Entity 423 Locked 424 Failed Dependency 426 Upgrade Required
  91. 91. 5xx Our Fault 500 Internal Server Error 501 Not Implemented 502 Bad Gateway 503 Service Unavailable 504 Gateway Timeout 505 HTTP Version Not Supported 506 Variant Also Negotiates 507 Insufficient Storage 508 Loop Detected 509 Bandwidth Limit Exceeded 510 Not Extended
  92. 92. Important HTTP features <ul><li>Caching
  93. 93. Conditional Requests
  94. 94. Content-Negotiation
  95. 95. Authentication </li></ul>
  96. 96. Caching GET /articles HTTP/1.1 Host: api.example.org HTTP/1.1 200 Ok Cache-Control: private; max-age=3600; must-revalidate Expires: Thu, 07 Apr 2011 01:30:00 GMT Last-Modified: Tue, 17 May 2011 04:58:08 GMT ETag: “e5199316748f31141d21498a29b25a7c” Pragma: no-cache Content-Type: text/html ..Content..
  97. 97. Caching GET /foo GET /foo 200 Ok 200 Ok
  98. 98. Caching GET /foo GET /foo 200 Ok 200 Ok GET /foo 200 Ok
  99. 99. Caching GET /articles HTTP/1.1 Host: api.example.org If-None-Match: “e5199316748f31141d21498a29b25a7c” If-Modified-Since: Tue, 17 May 2011 04:58:08 GMT HTTP/1.1 304 Not Modified Cache-Control: private; max-age=3600; must-revalidate Expires: Thu, 07 Apr 2011 01:30:00 GMT Last-Modified: Tue, 17 May 2011 04:58:08 GMT ETag: “e5199316748f31141d21498a29b25a7c” Note: If-None-Match & If-Modified-Since should not both appear in a request
  100. 100. Conditional Requests PUT /articles/123 HTTP/1.1 Host: api.example.org If-Match: “e5199316748f31141d21498a29b25a7c” If-Unmodified-Since: Tue, 17 May 2011 04:58:08 GMT HTTP/1.1 412 Precondition Failed Etag: “ac05a877f0043790da4a7d9672b0d4a9” <ul><li>Ensuring you're not overwriting others' changes. </li></ul>
  101. 101. Conditional Requests PUT /images/logo.png HTTP/1.1 Host: api.example.org If-Match: * HTTP/1.1 412 Precondition Failed <ul><li>Only create resources if they didn't already exist </li></ul>
  102. 102. ETag vs Last-Modified <ul><li>ETag is just string-matching
  103. 103. Dates allows for ranges </li><ul><li>But often not correctly implemented </li></ul><li>Dates are harder to parse
  104. 104. Dates are only accurate per-second </li></ul>
  105. 105. Content-Negotiation <ul><li>Any resource may have multiple representations
  106. 106. A client may prefer a specific representation
  107. 107. Multiple representations may include different languages, different file formats, encodings, etc. </li></ul>
  108. 108. Content-Negotiation GET /articles/123 HTTP/1.1 Accept: text/html, application/atom+xml Accept-Encoding: gzip Accept-Language: nl, en-GB, en, * Accept-Charset: utf-8 HTTP/1.1 200 Ok Content-Type: text/html; charset=utf-8 Content-Encoding: gzip Content-Language: nl-BE
  109. 109. Content-Negotiation Bad GET /articles/123.json?lang=nl HTTP/1.1 Good GET /articles/123 HTTP/1.1 Accept-Language: nl, en-GB, * Accept: application/json Accept-Encoding: gzip Accept-Charset: utf-8
  110. 110. Although.. GET /foo GET /foo 200 Ok 200 Ok
  111. 111. Although.. GET /foo GET /foo 200 Ok 200 Ok GET /foo 200 Ok
  112. 112. Although.. GET /foo GET /foo 200 Ok 200 Ok 200 Ok GET /foo
  113. 113. The Vary: header HTTP/1.1 200 Ok Content-Type: text/html; charset=utf-8 Content-Encoding: gzip Content-Language: nl-NL Vary: Accept-Language Vary: tells caches there may be variations in responses.
  114. 114. Authentication
  115. 115. Authentication Common schemes: <ul><li>Basic
  116. 116. Digest
  117. 117. OAuth </li></ul>
  118. 118. Authentication - Basic <ul><li>Very easy to implement
  119. 119. Widely supported
  120. 120. Very insecure without SSL
  121. 121. Password not hashed </li></ul>base64(username + ':' + password)
  122. 122. Authentication - Digest <ul><li>Widely supported
  123. 123. Password is hashed
  124. 124. Replay attack protection
  125. 125. Decent MiTM protection
  126. 126. Possibly increased roundtrips </li></ul>A1=md5(username:realm:password) A2=md5(request-method:request-uri) Digest=md5(A1:nonce:nc:cnonce:qop:A2)
  127. 127. Authentication - OAuth <ul><li>Popular for public API's
  128. 128. Now an RFC standard
  129. 129. Complicated for consumers
  130. 130. No full protection against replay attacks
  131. 131. Moving target </li></ul>
  132. 132. OAuth 3-legged auth User Consumer Service Provider
  133. 133. OAuth 2-legged auth <ul><li>Same API
  134. 134. Less authentication steps </li></ul>Resist the temptation Consumer Service Provider
  135. 135. Authentication Basic Digest OAuth Mitm protection Terrible Decent Decent Password encryption None Salted hash HMAC Ease of use Very Good Challenging Browser support Yes Yes No Increased roundtrips No Possibly No
  136. 136. Authentication Basic Digest OAuth Mitm protection Great Great Great Password encryption Encrypted, not hashed Great Great Ease of use Very Good Challenging Browser support Yes Yes No Increased roundtrips No Possibly No
  137. 137. Conclusion (1/2) REST is good for you, because: <ul><li>You can use a ton of software as-is
  138. 138. You don't have to reinvent the wheel
  139. 139. It's future compatible </li></ul>
  140. 140. Conclusion (2/2) If you're implementing a REST service <ul><li>Be pragmatic
  141. 141. Use standards where appropriate
  142. 142. Have no shame in using a sub- or superset of the standards. </li></ul>
  143. 143. Thank you! <ul><li>@evertp
  144. 144. http://joind.in/3231 </li></ul>

×