Your SlideShare is downloading. ×
Designing HTTP Interfaces and RESTful Web Services (PHPBNL11 2011-01-28)
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Designing HTTP Interfaces and RESTful Web Services (PHPBNL11 2011-01-28)


Published on

Published in: Technology
No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 2. David Zülke
  • 3. David Zuelke
  • 4.ünchen_Panorama.JPG
  • 5. Founder
  • 6. Lead Developer
  • 7. @dzuelke
  • 8. THE OLDEN DAYS Before REST Was En Vogue
  • 9.
  • 10. along came
  • 11.  dis is srs SEO bsns
  • 12. and said
  • 14. at least if they were
  • 15. so we had to change this
  • 16.
  • 17. and then things got out of control
  • 18. because nobody really had a clue
  • 19.
  • 20.
  • 21. oh dear…
  • 22. BUT HEYWhat about XML-RPC and SOAP?
  • 23. POST  /soapendpoint.php  HTTP/1.1Host:  localhostContent-­‐Type:  text/xml;  charset=utf-­‐8<?xml  version="1.0"  encoding="UTF-­‐8"?><SOAP-­‐ENV:Envelope  xmlns:SOAP-­‐ENV="">    <SOAP-­‐ENV:Body>        <ns1:getProduct  xmlns:ns1="">            <id>123456</id>        </ns1:getProduct>    </SOAP-­‐ENV:Body></SOAP-­‐ENV:Envelope>HTTP/1.1  200  OKContent-­‐Type:  text/xml;  charset=utf-­‐8<?xml  version="1.0"  encoding="UTF-­‐8"?><SOAP-­‐ENV:Envelope  xmlns:SOAP-­‐ENV="">    <SOAP-­‐ENV:Body>        <ns1:getProductResponse  xmlns:ns1="">            <product>                <id>123456</id>                <name>Red  Stapler</name>                <price>3.14</price>            </product>        </ns1:getProductResponse>    </SOAP-­‐ENV:Body></SOAP-­‐ENV:Envelope>
  • 24. POST  /soapendpoint.php  HTTP/1.1Host:  localhostContent-­‐Type:  text/xml;  charset=utf-­‐8<?xml  version="1.0"  encoding="UTF-­‐8"?><SOAP-­‐ENV:Envelope  xmlns:SOAP-­‐ENV="">    <SOAP-­‐ENV:Body>        <ns1:getProduct  xmlns:ns1="">            <id>987654</id>        </ns1:getProduct>    </SOAP-­‐ENV:Body></SOAP-­‐ENV:Envelope>HTTP/1.1  500  Internal  Service  ErrorContent-­‐Type:  text/xml;  charset=utf-­‐8<?xml  version="1.0"  encoding="UTF-­‐8"?><SOAP-­‐ENV:Envelope  xmlns:SOAP-­‐ENV="">    <SOAP-­‐ENV:Body>        <SOAP-­‐ENV:Fault>            <faultcode>SOAP-­‐ENV:Server</faultcode>            <faultstring>Unknown  Product  </faultstring>        </SOAP-­‐ENV:Fault>    </SOAP-­‐ENV:Body></SOAP-­‐ENV:Envelope>
  • 25. SOAP sucks, said everyone
  • 26. lets build APIs without the clutter, they said
  • 27. example: the API
  • 28. POST  /api/talk  HTTP/1.1Host:  joind.inContent-­‐Type:  text/xml;  charset=utf-­‐8<?xml  version="1.0"  encoding="UTF-­‐8"?><request>                <auth>                                <user>Chuck  Norris</user>                                <pass>roundhousekick</pass>                </auth>                <action  type="getdetail">                                <talk_id>42</talk_id>                </action></request>HTTP/1.1  200  OKContent-­‐Type:  text/xml;  charset=utf-­‐8<?xml  version="1.0"  encoding="UTF-­‐8"?><response>   <item>     <talk_title>My  Test  Talk</talk_title>     <talk_desc>This  is  a  sample  talk  description</talk_desc>     <ID>42</ID>   </item></response>
  • 29. PROBLEMS WITH THIS API• Always a POST• Doesnt use HTTP Authentication• Operation information is enclosed in the request ("getdetail")• Nothing there is cacheable• Everything through one endpoint (/api/talks for talks)
  • 30. Level 0 in the Richardson Maturity Model: Plain old XML over the wire in an RPC fashion
  • 31. Room for improvement: use one URI for each resource.
  • 32. That would be Level 1 in Richardsons Maturity Model
  • 33. Level 0 and Level 1 are a bag of hurt. Do not use them. Ever.
  • 35. that was awesome
  • 36. because everyone could say
  • 37.  I haz REST nao
  • 38. when in fact
  • 39. they bloody didn’t
  • 40. RESTWhat Does That Even Mean?
  • 41. REpresentational State Transfer
  • 42. Roy Thomas Fielding: Architectural styles andthe design of network based software architectures.
  • 43. REST CONSTRAINTS• Client-Server• Stateless• Cacheable• Layered System• Code on Demand (optional)• Uniform Interface
  • 44. Simple explaination of the Uniform Interface
  • 45. •A URL identifies a Resource• The URLs have an implicit hierarchy • so you know that something with additional slashes is a subordinate resource (HTTP spec)• Methods perform operations on resources• The operation is implicit and not part of the URL•A hypermedia format is used to represent the data• Link relations are used to navigate a service
  • 46. a web page is not a resource
  • 47. it is a (complete) representation of a resource
  • 48. GETTING JSON BACKGET  /products/  HTTP/1.1Host:  acme.comAccept:  application/jsonHTTP/1.1  200  OKContent-­‐Type:  application/json;  charset=utf-­‐8Allow:  GET,  POST[    {        id:  1234,        name:  "Red  Stapler",        price:  3.14,        location:  ""    }]
  • 49. GETTING XML BACKGET  /products/  HTTP/1.1Host:  acme.comAccept:  application/xmlHTTP/1.1  200  OKContent-­‐Type:  application/xml;  charset=utf-­‐8Allow:  GET,  POST<?xml  version="1.0"  encoding="utf-­‐8"?><products  xmlns="urn:com.acme.products"  xmlns:xl="">    <product  id="1234"  xl:type="simple"  xl:href="">        <name>Red  Stapler</name>        <price  currency="EUR">3.14</price>    </product></products>
  • 50. no hypermedia formats yet in those examples!
  • 51. I will show that in a few minutes
  • 52. AND FINALLY, HTMLGET  /products/  HTTP/1.1Host:  acme.comAccept:  application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5User-­‐Agent:  Mozilla/5.0  (Macintosh;  U;  Intel  Mac  OS  X  10_5_8;  en-­‐us)  AppleWebKit…HTTP/1.1  200  OKContent-­‐Type:  text/html;  charset=utf-­‐8Allow:  GET,  POST<html  lang="en">    <head>        <meta  http-­‐equiv="Content-­‐Type"  content="text/html;  charset=UTF-­‐8"></meta>        <title>ACME  Inc.  Products</title>    </head>    <body>        <h1>Our  Incredible  Products</h1>        <ul  id="products">            <li><a  href="">Red  Stapler</a>  (€3.14)</li>        </ul>    </body></html>
  • 53. VOLUME ONEDesigning an HTTP Interface
  • 54. A FEW EXAMPLESLet’s Start With Proper URL Design
  • 55. BAD URLS••• WTF?• new what?• sausage ID?•
  • 56. GOOD URLS a list of products• filtering is a query• a single product• all photos•••
  • 57. THE NEXT LEVELTime To Throw CRUD Into The Mix
  • 58. COLLECTION OPERATIONS• • GET to retrieve a list of products • POST to create a new product • returns • 201 Created • Location:
  • 59. ITEM OPERATIONS• • GET to retrieve • PUT to update • DELETE to, you guessed it, delete
  • 60. but please
  • 61. don’t use sessions IDs or cookies to maintain client state
  • 62. Now we are at Level 2 in RMM
  • 63. RMM LEVEL 2• Use HTTP verbs • GET (safe and idempotent) • POST (unsafe, not idempotent) • PUT & DELETE (unsafe, idempotent)• Use HTTP status codes to indicate result success • HTTP/1.1 409 Conflict
  • 64. TWITTERS “REST” API, DISSECTED(well, not the whole API; just the status methods will do)
  • 65. mind you were not even inspecting the RESTfulness
  • 66. were just looking at Twitters API from an HTTP perspective
  • 67. STATUSES/SHOW• GET• Problems: • Operation (“show”) included in the URL • Status ID not a child of the “statuses” collection• Better: GET with Accept header
  • 68. STATUSES/UPDATE• POST• Problems: • Operation (“update”) included in the URL • Uses the authenticated user implicitly• Better: POST
  • 69. STATUSES/DESTROY• POST• Problems: • Operation (“destroy”) included in the URL like it’s 1997 • Odd, illogical hierarchy again • Allows both “POST” and “DELETE” as verbs• Better: DELETE
  • 70. STATUSES/RETWEETS• GET• Problems: • Hierarchy is wrong• Better: GET
  • 71. STATUSES/RETWEET• PUT• Problems: • “retweets” collection exists, but is not used here • As usual, the action is in the URL (“make retweet” is RPC-y) • Allows both “PUT” and “POST” as verbs• Better: POST
  • 72. SUMMARY• • POST to create a new tweet• • DELETE deletes, PUT could be used for updates• • POST creates a new retweet
  • 73. ANGRY GERMAN SUMMARY• Twitters "REST" API is crap, sucks, and even hates HTTP
  • 74. VOLUME TWODesigning a RESTful Service
  • 75. THE UNIFORM INTERFACE• Identification of Resources (e.g. through URIs) • Representations are conceptually separate!• Manipulation Through Representations (i.e. they are complete)• Self-Descriptive Messages (containing all information)• Hypermedia As The Engine Of Application State ("HATEOAS")
  • 76. HATEOASThe Missing Piece in the Puzzle
  • 77. ONE LAST PIECE IS MISSING• How does a client know what to do with resources?• How do you go to the “next” operation?• What are the URLs for creating subordinate resources?• Where is the contract for the service?
  • 78. HYPERMEDIA AS THE ENGINE OF APPLICATION STATE• Use links to allow clients to discover locations and operations• Link relations are used to express the possible options• Clients do not need to know 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!
  • 79. XHTML and Atom are Hypermedia formats
  • 80. Or you roll your own...
  • 81. A CUSTOM MEDIA TYPEGET  /products/1234  HTTP/1.1Host:  acme.comAccept:  application/vnd.acmecorpshop+xml more info for clients re-use Atom forHTTP/1.1  200  OKContent-­‐Type:  application/vnd.acmecorpshop+xml;  charset=utf-­‐8 link relationsAllow:  GET,  PUT,  DELETE<?xml  version="1.0"  encoding="utf-­‐8"?><product  xmlns="urn:com.acme.prods"  xmlns:atom="">    <id>1234</id>    <name>Red  Stapler</name>    <price  currency="EUR">3.14</price>    <atom:link  rel="payment"  type="application/vnd.acmecorpshop+xml"                          href=""/></product> meaning defined in Atom standard!
  • 82. boom, RMM Level 3
  • 83. XML is really good for hypermedia formats
  • 84. (hyperlinks, namespaced attributes, re-use of formats, …)
  • 85. JSON is more difficult
  • 86. (no hyperlinks, no namespaces, no element attributes)
  • 87. XML VERSUS JSON<?xml  version="1.0"  encoding="utf-­‐8"?><product  xmlns="urn:com.acme.prods"  xmlns:atom="">    <id>1234</id>    <name>Red  Stapler</name>    <price  currency="EUR">3.14</price>    <atom:link  rel="payment"  type="application/vnd.acmecorpshop+xml"                          href=""/></product>{    id:  1234,    name:  "Red  Stapler",    price:  {        amount:  3.14,        currency:  "EUR"    },    links:  [        {            rel:  "payment",            type:  "application/vnd.acmecorpshop+xml",            href:  ""        }    ]}
  • 88. and hey
  • 89. without hypermedia, your HTTP interface is not RESTful
  • 90. that’s totally fineand sometimes even the only way to do it
  • 91. (e.g. CouchDB or S3 are never going to be RESTful)
  • 92. but don’t you dare call it a RESTful interface ;)
  • 93. one more hypermedia format example: the Lovefilm API
  • 94. <?xml  version="1.0"  encoding="utf-­‐8"  standalone="yes"?><search>    <total_results>6</total_results>    <items_per_page>2</items_per_page>    <start_index>1</start_index>    <link  href=";items_per_page=2&amp;term=old"                rel="self"  title="self"/>    <link  href=";items_per_page=2&amp;term=old"                rel="next"  title="next"/>    <link  href=";items_per_page=2&amp;term=old"                rel="last"  title="last"/>    <catalog_title>        <can_rent>true</can_rent>        <release_date>2003-­‐09-­‐12</release_date>        <title  full="Star  Wars:  Knights  of  the  Old  Republic"  clean="Star  Wars:  Knights  of  the  Old  Republic"/>        <id></id>        <adult>false</adult>        <number_of_ratings>574</number_of_ratings>        <rating>4</rating>        <category  scheme=""  term="games"/>        <category  scheme=""  term="Xbox"/>        <category  scheme=""  term="Adventure"/>        <category  scheme=""  term="Role-­‐playing"/>        <category  scheme=""  term="TBC"/>        <link  href=""                    rel=""  title="synopsis"/>        <link  href=""                    rel=""  title="reviews"/>        <link  href="­‐Star-­‐Wars-­‐Knights-­‐of-­‐the-­‐Old-­‐Republic.html?cid=LFAPI"                    rel="alternate"  title="web  page"/>    </catalog_title></search>
  • 95. does not yet use a custom media type, hope theyll fix that
  • 96. HOSTS AND VERSIONING• Q: Why not ? • A: Because and http:// would be different resources!• Q: What about /1/ or /2/ for versioning? • A: Again, different resources. Instead, use the media type: application/ or application/;ver=2
  • 97. YOU MIGHT BE WONDERING Why Exactly Is This Awesome?
  • 98. THE MERITS OF REST• Easyto evolve: add new • Easyto implement: build it features or elements without on top of HTTP, and profit! breaking BC • Authentication & TLS• Easy to learn: developers can "browse" service via link rels • Caching & Load Balancing• Easyto scale up: grows well • Conditional Requests with number of features, users and servers • Content Negotiation
  • 99. but...
  • 100. hold on, you say
  • 101. a plain HTTP-loving service does the job, you say
  • 102. surely, there is a merit to REST beyond extensibility, you ask
  • 103. nope
  • 104. "REST is software design on the scale of decades: everydetail is intended to promote software longevity andindependent evolution. Many of the constraints aredirectly opposed to short-term efficiency. Unfortunately,people are fairly good at short-term design, and usuallyawful at long-term design." Roy Fielding
  • 105. "Most of RESTs constraints are focused on preservingindependent evolvability over time, which is onlymeasurable on the scale of years. Most developerssimply dont care what happens to their product yearsafter it is deployed, or at least they expect to be aroundto rewrite it when such change occurs." Roy Fielding
  • 106. FURTHER READING• Ryan Tomayko How I Explained REST to my Wife• Jim Webber, Savas Parastatidis & Ian Robinson How to GET a Cup of Coffee• Roy Thomas Fielding Architectural Styles and the Design of Network-based Software Architectures
  • 107. BOOKS ON REST• Jim Webber, Savas Parastatidis, Ian Robinson REST in Practice ISBN: 978-0596805821• Subbu Allamaraju RESTful Web Services Cookbook ISBN: 978-0596801687• Leonard Richardson, Sam Ruby RESTful Web Services ISBN: 978-0596529260
  • 108. !e End
  • 109. Questions?
  • 110. THANK YOU! This was by @dzuelkeSend me questions or hire