Understanding REST and designing for itRESTful Design
Robert MacLeanwww.sadev.co.za@rmacleanBB&D ATCIntroductionHTTP BasicsURI’sMethodsStatus CodesContent TypeAuthenticationURI PlanningPatternsStyleAccidental ServicesExamplesActionsGuidelinesAnti-PatternsSecurityWrap UpAbout meAgendaWelcome
RESTAcronym? Representational State Transfer Source?Came about in 2000 doctoral dissertation of Roy Fielding
What is it?ROA – Resource Orientated ArchitectureWOA – Web Orientated ArchitectureThanks Gartner for another TLA It is a styleNOT APIInterfaceOfficial StandardA drop in replacement for SOAP
Benefits of RESTHighly scalableDesigned for HTTPEasy to consume & produceNo complex request/response model.No complex XML contractsEasy to understand for you and machinesURI + Method = Intent
HTTP BasicsREST builds on HTTP so you need to know HTTPHTTP is not HTMLHTTP is statelessHTTPURIHeaderhttp://www.sadev.co.zaMethodGETStatus Code200Content Typetext/plainBodytext
URI BasicsHostnameSchemeQueryhttp://www.sadev.co.za/users/1/contacthttp://www.sadev.co.za?user=1&action=contacthttp://rob:pass@bbd.co.za:8044https://bbd.co.za/index.html#aboutQueryHostnameSchemeUserinfoHostnamePortSchemeSchemeHostnameQueryFragment
Method BasicsJust a guide
Status Codes1xx – Informational 2xx – Success3xx – Redirection4xx – Client Error5xx – Server Error
Status Codes Examples100 = Continue102 = Processing200 = OK201 = Created204 = No Content206 = Partial Content301 = Moved Permanently 302 = Found (Moved Temp)307 = Temp Redirect400 = Bad Request401 = Unauthorised402 = Payment Required403 = Forbidden404 = Not Found405 = Method Not Allowed409 = Conflict418 = I’m a teapot450 = Blocked by Windows Parental Controls500 = Internal Server Error501 = Not Implemented
Content TypeProper name: Internet Media TypeAlso known as MIME typeParts: Type, SubType, Optional Parametersx- prefix for nonstandard types or subtypesvnd. prefix for vendor specific subtypesFrowned upon by purists
Content Type Examplestext/plain 			– Plain texttext/xml 			– XML text/html 			– HTML image/png 			– PNG imageaudio/basic 			– Wave audioaudio/mpeg 			– MPEG audio (MP3)video/quicktime 			– Quicktime Videoapplication/pdf 			– Adobe PDF documentapplication/javascript 		– JavaScriptapplication/vnd.ms-powerpoint 	– PowerPoint fileapplication/x-rar-compressed 	– RAR file
HTTP AuthenticationBasic AuthenticationEasy to do, but plain text. Easy to reverse engineer. Less of an issue when used with SSL.Digest AuthenticationHarder to do, still plain text. Hard (impossible?) to reverse engineer because of hashing. NTLM AuthenticationHard to do, Windows specific. Hard (impossible?) to reverse engineer.
Header ExampleRequestHEAD /index.htmlHTTP/1.1 Host: www.example.com ResponseHTTP/1.1 200 OK Date: Mon, 23 May 2005 22:38:34 GMT Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux) Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT Etag: "3f80f-1b6-3e1cb03b" Accept-Ranges: bytes Content-Length: 438 Connection: close Content-Type: text/html; charset=UTF-8
Lego CatalogueA simple system to store what LEGO’s a person owns. Want toAdd bricksSet bricks status to be in useRemove bricksGet list of bricksCheck if I have enough bricksGet picture of brick
Lego Catalogue URIHTTP ValidREST ValidIntent good
Lego Catalogue URIHTTP ValidREST ValidIntent good
Lego Catalogue URIHTTP ValidREST ValidIntent good
Lego Catalogue URIHTTP ValidREST InvalidIntent bad
Lego Catalogue URIHTTP ValidREST InvalidIntent nightmare
Real Life URI ExampleResource: PhotosWhere:http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}.jpghttp://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}_[mstb].jpghttp://farm{farm-id}.static.flickr.com/{server-id}/{id}_{o-secret}_o.(jpg|gif|png)What: JPEG, GIF or PNG (defined in the URL)http://farm1.static.flickr.com/2/1418878_1e92283336_m.jpg
REST Method Style“The big four”
Accidental ServicesAccidental services do not use all methodsSome URL’s offering all of them and others a limited set
Methods Examplehttp://bbddb01/northwind/users[firstname=“rob%”]+ POST = Error + GET = Returns everyone who begins with rob+ PUT = Error+ DELETE = Deletes everyone who begins with robhttp://bbddb01/northwind/users+ we add some input data+ POST = Creates a new user+ GET = Returns everyone who meets criteria+ PUT = Creates/Updates a user (based on data)+ DELETE = Deletes everyone who meets criteria
Methods Examplehttp://bbddb01/northwind/users[firstname=“rob%”]+ POST = Error + PUT = ErrorWhat would the error be?HTTP 400 would be best405 or 500 could also be appropriate
What about actions?GetStoreOpenTime(Location)GET http://lc/stores/{location}/times?state=openRejectDesign(Design)POST http://lc/rejections + form dataPerformBrickCount(Design)POST http://lc/design/124/brickCountGET http://lc/design/124/brickCount/2
GuidelinesDesign to be statelessDesign for resources, not servicesStock quote service vs. A way to work with stock resourcesUse cookies for self-contained state
GuidelinesNaming: Favour nouns over verbsGET /brick/2/deleteDELETE /brick/2Shorter nice URI’s preferred, not requiredDo not change URI’sUse 3xx redirection if needed
GuidelinesGive every resource an IDhttp://lc/brick/1http://lc/project/planned/223More URI’s the better
GuidelinesSupport for multiple data types or representationsFor data use XML and/or JSONPostfixes to define typeGET /brick/2/image.jpgGET /brick/2/image.png
GuidelinesDesign with standards in mind – for example RSS & ATOMCreate should return URI’s not resourcesUse the right HTTP methods for the right actionsYou are on HTTP – use the infrastructure.Proxy, Caching, Etag, Expires
GuidelinesHyperlinks are good<project self=“http://lc/project/753”> <bricksUsed>   <brick ref=“http://lc/brick/234” />    <brick ref=“http://lc/brick/286” /><brick ref=“http://lc/brick/12” /> </bricksUsed> <coloursUsed>   <colour name=“red” code=“ff0000” ref=“http://lc/brick/red”/>  </coloursUsed></project>
GuidelinesOffer paging<bricks self=“http://lc/bricks”> <link rel=“next” ref=“http://lc/bricks?page=20” /> …</bricks>
GuidelinesOffer collections of information<bricks> <brick ref=“http://lc/brick/1” /> <brick ref=“http://lc/brick/2” /><brick ref=“http://lc/brick/3” /></brick><bricks>  <brick ref=“http://lc/brick/1”>    <colour>red</colour> </brick>  <brick ref=“http://lc/brick/2”><colour>red</colour>  </brick>  <brick ref=“http://lc/brick/3”><colour>red</colour>  </brick></brick>
Anti-PatternsUse one HTTP method – like GET for everythingOften called GET or POST TunnellingPass everything in URI’sAssume this is a replacement for SOAP or WS*
Security101Are RESTful services secure?It’s a style, not a technology so that depends on how you implement it.Are you open to SQL injection attacks?When you look at http://bbddb01/northwind/users[firstname=“rob%”], you may think so but you shouldn’t be. Because:The parameter shouldn’t be SQLIf it is SQL, why are you not filtering it?Remember the old rule: Do not trust user inputURI’s are user input
Security102How can I do authentication?It’s built on HTTP, so everything you have for authentication in HTTP is availablePLUSYou could encode your authentication requirements into the input fields
Good ExamplesWCF Data ServicesPreviously called ADO.NET Data Services & AstoriaNerdDinner.comTwitter.comMediaWikiTheir action’s are frowned upon by purists
Benefits of RESTHighly scalableDesigned for HTTP and statelessEasy to consumeNo complex request/response model.No complex XML contractsEasy to understand for you and machinesURI + Method = Intent

RESTful design

  • 1.
    Understanding REST anddesigning for itRESTful Design
  • 2.
    Robert MacLeanwww.sadev.co.za@rmacleanBB&D ATCIntroductionHTTPBasicsURI’sMethodsStatus CodesContent TypeAuthenticationURI PlanningPatternsStyleAccidental ServicesExamplesActionsGuidelinesAnti-PatternsSecurityWrap UpAbout meAgendaWelcome
  • 3.
    RESTAcronym? Representational StateTransfer Source?Came about in 2000 doctoral dissertation of Roy Fielding
  • 4.
    What is it?ROA– Resource Orientated ArchitectureWOA – Web Orientated ArchitectureThanks Gartner for another TLA It is a styleNOT APIInterfaceOfficial StandardA drop in replacement for SOAP
  • 5.
    Benefits of RESTHighlyscalableDesigned for HTTPEasy to consume & produceNo complex request/response model.No complex XML contractsEasy to understand for you and machinesURI + Method = Intent
  • 6.
    HTTP BasicsREST buildson HTTP so you need to know HTTPHTTP is not HTMLHTTP is statelessHTTPURIHeaderhttp://www.sadev.co.zaMethodGETStatus Code200Content Typetext/plainBodytext
  • 7.
  • 8.
  • 9.
    Status Codes1xx –Informational 2xx – Success3xx – Redirection4xx – Client Error5xx – Server Error
  • 10.
    Status Codes Examples100= Continue102 = Processing200 = OK201 = Created204 = No Content206 = Partial Content301 = Moved Permanently 302 = Found (Moved Temp)307 = Temp Redirect400 = Bad Request401 = Unauthorised402 = Payment Required403 = Forbidden404 = Not Found405 = Method Not Allowed409 = Conflict418 = I’m a teapot450 = Blocked by Windows Parental Controls500 = Internal Server Error501 = Not Implemented
  • 11.
    Content TypeProper name:Internet Media TypeAlso known as MIME typeParts: Type, SubType, Optional Parametersx- prefix for nonstandard types or subtypesvnd. prefix for vendor specific subtypesFrowned upon by purists
  • 12.
    Content Type Examplestext/plain – Plain texttext/xml – XML text/html – HTML image/png – PNG imageaudio/basic – Wave audioaudio/mpeg – MPEG audio (MP3)video/quicktime – Quicktime Videoapplication/pdf – Adobe PDF documentapplication/javascript – JavaScriptapplication/vnd.ms-powerpoint – PowerPoint fileapplication/x-rar-compressed – RAR file
  • 13.
    HTTP AuthenticationBasic AuthenticationEasyto do, but plain text. Easy to reverse engineer. Less of an issue when used with SSL.Digest AuthenticationHarder to do, still plain text. Hard (impossible?) to reverse engineer because of hashing. NTLM AuthenticationHard to do, Windows specific. Hard (impossible?) to reverse engineer.
  • 14.
    Header ExampleRequestHEAD /index.htmlHTTP/1.1Host: www.example.com ResponseHTTP/1.1 200 OK Date: Mon, 23 May 2005 22:38:34 GMT Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux) Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT Etag: "3f80f-1b6-3e1cb03b" Accept-Ranges: bytes Content-Length: 438 Connection: close Content-Type: text/html; charset=UTF-8
  • 15.
    Lego CatalogueA simplesystem to store what LEGO’s a person owns. Want toAdd bricksSet bricks status to be in useRemove bricksGet list of bricksCheck if I have enough bricksGet picture of brick
  • 16.
    Lego Catalogue URIHTTPValidREST ValidIntent good
  • 17.
    Lego Catalogue URIHTTPValidREST ValidIntent good
  • 18.
    Lego Catalogue URIHTTPValidREST ValidIntent good
  • 19.
    Lego Catalogue URIHTTPValidREST InvalidIntent bad
  • 20.
    Lego Catalogue URIHTTPValidREST InvalidIntent nightmare
  • 21.
    Real Life URIExampleResource: PhotosWhere:http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}.jpghttp://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}_[mstb].jpghttp://farm{farm-id}.static.flickr.com/{server-id}/{id}_{o-secret}_o.(jpg|gif|png)What: JPEG, GIF or PNG (defined in the URL)http://farm1.static.flickr.com/2/1418878_1e92283336_m.jpg
  • 22.
  • 23.
    Accidental ServicesAccidental servicesdo not use all methodsSome URL’s offering all of them and others a limited set
  • 24.
    Methods Examplehttp://bbddb01/northwind/users[firstname=“rob%”]+ POST= Error + GET = Returns everyone who begins with rob+ PUT = Error+ DELETE = Deletes everyone who begins with robhttp://bbddb01/northwind/users+ we add some input data+ POST = Creates a new user+ GET = Returns everyone who meets criteria+ PUT = Creates/Updates a user (based on data)+ DELETE = Deletes everyone who meets criteria
  • 25.
    Methods Examplehttp://bbddb01/northwind/users[firstname=“rob%”]+ POST= Error + PUT = ErrorWhat would the error be?HTTP 400 would be best405 or 500 could also be appropriate
  • 26.
    What about actions?GetStoreOpenTime(Location)GEThttp://lc/stores/{location}/times?state=openRejectDesign(Design)POST http://lc/rejections + form dataPerformBrickCount(Design)POST http://lc/design/124/brickCountGET http://lc/design/124/brickCount/2
  • 27.
    GuidelinesDesign to bestatelessDesign for resources, not servicesStock quote service vs. A way to work with stock resourcesUse cookies for self-contained state
  • 28.
    GuidelinesNaming: Favour nounsover verbsGET /brick/2/deleteDELETE /brick/2Shorter nice URI’s preferred, not requiredDo not change URI’sUse 3xx redirection if needed
  • 29.
    GuidelinesGive every resourcean IDhttp://lc/brick/1http://lc/project/planned/223More URI’s the better
  • 30.
    GuidelinesSupport for multipledata types or representationsFor data use XML and/or JSONPostfixes to define typeGET /brick/2/image.jpgGET /brick/2/image.png
  • 31.
    GuidelinesDesign with standardsin mind – for example RSS & ATOMCreate should return URI’s not resourcesUse the right HTTP methods for the right actionsYou are on HTTP – use the infrastructure.Proxy, Caching, Etag, Expires
  • 32.
    GuidelinesHyperlinks are good<projectself=“http://lc/project/753”> <bricksUsed> <brick ref=“http://lc/brick/234” /> <brick ref=“http://lc/brick/286” /><brick ref=“http://lc/brick/12” /> </bricksUsed> <coloursUsed> <colour name=“red” code=“ff0000” ref=“http://lc/brick/red”/> </coloursUsed></project>
  • 33.
    GuidelinesOffer paging<bricks self=“http://lc/bricks”><link rel=“next” ref=“http://lc/bricks?page=20” /> …</bricks>
  • 34.
    GuidelinesOffer collections ofinformation<bricks> <brick ref=“http://lc/brick/1” /> <brick ref=“http://lc/brick/2” /><brick ref=“http://lc/brick/3” /></brick><bricks> <brick ref=“http://lc/brick/1”> <colour>red</colour> </brick> <brick ref=“http://lc/brick/2”><colour>red</colour> </brick> <brick ref=“http://lc/brick/3”><colour>red</colour> </brick></brick>
  • 35.
    Anti-PatternsUse one HTTPmethod – like GET for everythingOften called GET or POST TunnellingPass everything in URI’sAssume this is a replacement for SOAP or WS*
  • 36.
    Security101Are RESTful servicessecure?It’s a style, not a technology so that depends on how you implement it.Are you open to SQL injection attacks?When you look at http://bbddb01/northwind/users[firstname=“rob%”], you may think so but you shouldn’t be. Because:The parameter shouldn’t be SQLIf it is SQL, why are you not filtering it?Remember the old rule: Do not trust user inputURI’s are user input
  • 37.
    Security102How can Ido authentication?It’s built on HTTP, so everything you have for authentication in HTTP is availablePLUSYou could encode your authentication requirements into the input fields
  • 38.
    Good ExamplesWCF DataServicesPreviously called ADO.NET Data Services & AstoriaNerdDinner.comTwitter.comMediaWikiTheir action’s are frowned upon by purists
  • 39.
    Benefits of RESTHighlyscalableDesigned for HTTP and statelessEasy to consumeNo complex request/response model.No complex XML contractsEasy to understand for you and machinesURI + Method = Intent