Rest in practice


Published on

Presentation on REST given on EPAM Software Engineering Conference in 2013, Minsk.

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Roy Fielding & hisdissertationOne of theprincipalauthorsof HTTP specCo-founder of Apache HTTP server projectWasheavilyinvolvedin HTML and URIsDissertationNo mention of CRUD or POSTLater Fielding saysinhisblogthateven HTTP itself is not a mandatory part of REST (but URI is)HATEOAS is more importantthan CRUD (hypertextdrivesappstatechanges; contentnegotiation)Layeredsystem: gateways, loadbalancers, firewalls, sharedcaches, etc.
  • Per Roy F: fromlevel 0-2 it’s not REST, 3 IS REST … thetermREST has beenmostlycoupledwithCRUD-likeaccesstodomainobjects0 – URI tunneling:oneURI, one HTTP method POST to a single URI, allattributesasparameter  lookslike SOAP w/o envelope  part of the Web, limited use of availablefeaturesFirewallfriendly (HTTP)Lackssophistication1 – resources … manyURIs, one HTTP method  lots of thought-to-be-RESTfulservices  stilltoocomplex2 – verbs … manyURIs, many HTTP methods  verynice, butstill limited to CRUD scenariosonly3 – hypermedia  resourcesdescribetheirowncapabilities and interconnections  it’s like a HTML pagefromwhereyoucan go vialinks  inadditiontolinks, it’s alsoaboutcontentnegotiation – own (MIME) types, dynamicdiscoveryLevel 1 tackles the question of handling complexity by using divide and conquer, breaking a large service endpoint down into multiple resources.Level 2 introduces a standard set of verbs so that we handle similar situations in the same way, removing unnecessary variation.Level 3 introduces discoverability, providing a way of making a protocol more self-documenting.
  • Itcan be anythingelsethan XML, really (JSON, YAML, etc)RPC-stylesolutionBasicallylike SOAP
  • PronounciationHate o’sHateyo’ assHate eeohsExamples:Get the second 50 items from 500, we may get a link back to the first 50 as well as the thirdWe get the resource data along with possible actions we may take upon it  these actions may depend on my authority (authorization)  great JSON example + mention of Gateway API  good XML example  link tonew comment, commentstoblogentry + toselfproblems that it solves- w3c: coolurisdon’t change  calls return with content in a requested format  these formats have their media types with hints (links) as to what clients can do with the resource  application state may change while „jumping” from one resource to another  self-descriptive messagesREST APIs require the user to know that fixed URL structure (i.e. conventions)  client rewrite is needed when API changesWith SOAP clients figure out what they can do with a given resource from the WSDL  client-side (SOAP) vs server-side (HATEOAS)  fixed vs dynamicproblems that it causesMany applications simply map their backend (DB) object to HTTP (api)  resources != domain objects  resources == domain objects + metadataNew resource definitions might (and should) have their own MIME typesProblemsPeopledon’t understandit’s a problemNo tooling for thisLinkscould be part of theresponseheader 
  • Each slot now has a link element which contains a URI to tell us how to book an appointment.
  • SOAPProtocolvsarchitecturalstyle SOAP has a standard whereas REST doesn’tOperationsvsresources verbsvsnounsRigid (typecheckingin SOAP – sometimesit’s a goodthing), light-weight (REST needs no wrapper, like XML in SOAP)Non-intuitivenessvssimplicity  in REST URL describes almost everything and quiteintuitivetouse & modifySecurity: WS-Securityvs HTTPS/TLS  message-levelvstunnel-levelsecurity   ACID transactions over a serviceManyproxiesblock PUT (badto REST)
  • Safety & Idempotencysafe: no side-effectsIdempotent: can be repeatedinsuccessionwithoutfailureGET is safe and idempotentPUT and DELETE arenotsafe, butidempotentPOST is neithersafenoridempotentAssociationbetweenresources: /owners/123/dogs don’t go deeperthan /resource/identifier/resourceUse ‚?’ for attributes  /dogs?color=blackBe consistent, no mixed plurals&singularsConcretethingslikecoffee, beer NOT drink
  • version # asmuchinthe front aspossibleMajor version # onlyDatesas version #s  long, hardtoremember, whichdateformat?Optionalversioning and alwaystakethelatestifomitted
  • 200 – OK201 – created204 – No content (after DELETE)400 – Badrequest401 – unauthorized403 – Forbidden404 – notfound405 – methodnotallowed500 – internalerror503 – Service unavailablewithRetry-AfterheaderUltimatelythefollowingthreeshould be enough: 200, 400 (pointingourwherevalidationfailed) and 500
  • JSON wins over otherformats, like XML
  • PATCH -
  • Session managementCaching – reducenetworktraffic, loadon servers, latency, hidenetworkfailuresLocal cache + server cacheActions in the absence of resources  use verbs, like /currencyconverter/convert?from=EUR&to=BYR&amount=1000
  • Thingsremovedfrom here tokeeptime:PATCH - noteveryoneknowswhat HTTP methodsare forParameters/attributes in URL or as part of HTTP header  much easier to develop if in URLSuppress HTTP response codes  usefulwhenourcode is runningin a containerthatintercepts HTTP commslike status codes
  • Wadl – web applicationdescriptionlanguage (, wadl2java tool
  • Spring Data REST (SDR) representsthebottom-upapproach, whereSDRcomesfromthedomainobjectlayer … it’s notreallyRESTful, imo
  • Has beenintheindustrysince 1998Developer, tester, architect, project managerMobile, enterpriseForum nokiachampion(?), blogger
  • Rest in practice

    1. 1. GETGábor Török @ EPAM/Szeged
    2. 2.  Introduction, overview Best practices Java support
    3. 3.  Roy T Fielding, PhD dissertation, 2000 Main characteristics ◦ Client-server ◦ Stateless ◦ Caching ◦ Layered architecture ◦ Code on demand ◦ URIs
    4. 4. Richardson’s Maturity Model Image courtesy of Martin Fowler
    5. 5.  Plain Old XML (over HTTP) One URI, one method
    6. 6. POST /appointmentService HTTP/1.1<openSlotRequest date="2010-01-04" doctor="mjones"/>
    7. 7. Level 0: POX responseHTTP/1.1 200 OK<openSlotList> <slot start="1400" end="1450"> <doctor id="mjones"/> </slot> <slot start="1600" end="1650"> <doctor id="mjones"/> </slot></openSlotList>
    8. 8. POST /appointmentService HTTP/1.1<appointmentRequest> <slot doctor="mjones" start="1400" end="1450"/> <patient id="jsmith"/></appointmentRequest>
    9. 9. Level 0: POX responseHTTP/1.1 200 OK<appointment> <slot doctor="mjones" start="1400" end="1450"/> <patient id="jsmith"/></appointment>
    10. 10. Many URIs, one method
    11. 11. POST /doctors/mjones HTTP/1.1<openSlotRequest date="2010-01-04"/>
    12. 12. Level 1: Resources responseHTTP/1.1 200 OK<openSlotList> <slot id="1234" doctor="mjones" start="1400" end="1450"/> <slot id="5678" doctor="mjones" start="1600" end="1650"/></openSlotList>
    13. 13. POST /slots/1234 HTTP/1.1<appointmentRequest> <patient id="jsmith"/></appointmentRequest>
    14. 14. Level 1: Resources responseHTTP/1.1 200 OK<appointment id="2468"> <slot id="1234" doctor="mjones" start="1400" end="1450”/> <patient id="jsmith"/></appointment>
    15. 15.  Many URIs, many (HTTP) methods This is what most call REST Best practices follow
    16. 16. GET/doctors/mjones/slots?date=20100104&status=open HTTP/1.1
    17. 17. Level 2: Verbs responseHTTP/1.1 200 OK<openSlotList> <slot id="1234" doctor="mjones" start="1400" end="1450"/> <slot id="5678" doctor="mjones" start="1600" end="1650"/></openSlotList>
    18. 18. POST /slots/1234 HTTP/1.1<appointmentRequest> <patient id="jsmith"/></appointmentRequest>
    19. 19. Level 2: Verbs responseHTTP/1.1 200 OK<appointment id="2468"> <slot id="1234" doctor="mjones" start="1400" end="1450”/> <patient id="jsmith"/></appointment>
    20. 20. W3: „Cool URIs don’t change” vsRoy Fielding: „A REST API must not define fixed resource names or hierarchies” HATEOAS & self-descriptive messages Problems: people’s awareness, tools
    21. 21. Level 3: Hypermedia responseHTTP/1.1 200 OK<openSlotList> <slot id="1234" doctor="mjones” start="1400" end="1450"> <link rel="/linkrels/slot/book" uri="/slots/1234"/> </slot> …</openSlotList>
    22. 22. Level 3: Hypermedia responseHTTP/1.1 201 CreatedLocation: http://.../slots/1234/appointment<appointment> <slot id="1234" …/> <patient id="jsmith"/> <link rel="/linkrels/appointment/cancel" uri="/slots/1234/appointment"/> <link rel="self" uri="/slots/1234/appointment"/></appointment>
    23. 23. Solves interop problems WSDL contract Strong typing Client- and server bindings Operations (i.e. verbs)WS-* support (Security, GETing/POSTing an XMLAtomicTransaction, etc.)Many proxies block PUT Non-intuitive Level 0
    24. 24.  Resources vs actionsgetTickets vs /ticketsgetMusemTickets vs /tickets?type=museum
    25. 25. Plural + IDCRUD-style operationsConcrete not abstract namesResource GET POST PUT DELETE/tickets List tickets Create a Bulk update Delete all new ticket tickets/tickets/123 Get the Error Update a Delete a details of given ticket given ticket one ticket
    26. 26.  Major rev only Numbers, not nicknames, dates, etc.
    27. 27.  HTTP status codes 200 403 500 503 204 200 400 201 400 500 404 405 401 Short description Pointer to more information
    28. 28. HTTP Status Code: 401{ "status" : "401", "message":"Authenticate", "code": 12345, "more info": }
    29. 29.  Ways to differentiate: /tickets/123.json /tickets/123?format=json Accept: application/json Bonus: application/company.v1+json
    30. 30.  Pagination: /tickets?offset=50&limit=25 Partial response: /tickets?fields=date,location Use defaults (documentation!)
    31. 31.  Session management – REST is stateless Caching – it’s very much encouraged! What if nouns are not appropriate – use verbs
    32. 32.  Security – preferred is OAuth, lot of Basic/Digest over HTTPS in practice Subdomains: ◦ api ◦ developers for SDK Clean REST
    33. 33.  JSR 311: Java API for RESTful Web Services Annotation-driven@GET, @Path, @PathParam, @Consumes ImplementationsJersey, Restlet, RESTeasy, Apache CXF Jax-rs-hateoas
    34. 34. jax-rs
    35. 35.  Spring MVC application essentially Annotation-driven + XML configuration@RequestMapping et al. + viewresolvers, message converters, et al. spring-hateoas
    36. 36. spring mvc
    37. 37.  CRUD for JPA-entities using REST semantics @RestResource Pagination and sorting support spring-hateoas
    38. 38. spring data
    39. 39.  Roy Fielding’s dissertation REST in Practice from O’Reilly Apigee blog & video tutorials Articles, forums
    40. 40.  Levels of REST – REST ≠ CRUD Consistent view of best practices Java support
    41. 41.  Has been in the industry since late ’90s Has been @EPAM since 2009, acted as a Dev Lead/PM, now Solutions Architect Has mobile + enterprise background