best practices for architecting a pragmatic web api

Download Best Practices for Architecting a Pragmatic Web API

If you can't read please download the document

Upload: mario-cardinal

Post on 10-May-2015

24.503 views

Category:

Technology


0 download

DESCRIPTION

This presentation teach how to design a real-world and pragmatic web API. It draws from the experience Mario Cardinal have gained over the years being involved architecting many Web API. This presentation begins by differencing between a Web and a REST API, and then continue with the design process. We conclude with the core learnings of the session which is a review of the best practices when designing a web API. Armed with skills acquired, you can expect to see significant improvements in your ability to design a pragmatic web API.

TRANSCRIPT

  • 1.Best Practices for Architectinga Pragmatic Web APIMario CardinalAgile Coach & Software Architectwww.mariocardinal.com@mario_cardinalOctober 15

2. Who am I? Agile Coach & Software architect Co-Founder of Slingboards Lab http://mariocardinal.com 3. 3Content1. REST What is it?2. RESTful or Resource APIs?3. Resource APIs or Web APIs?4. Web APIs Best practices 4. Application Programming Interface (API) A Web API is a software intermediary that makesit possible for application programs to interactwith each other and share data. Often an implementation of REST that exposes aspecific software functionality. Simple, intuitive and consistent. Friendly to the developer. Explorable via HTTP tool.4API 5. REST What is it? An architectural style (extends client-server)introduced by Roy Fielding Defines a set of constraints influenced fromthe architecture of the Web URLs represent resources Clients interact with resources via a uniforminterface Messages are self-descriptive (ContentType) Services are stateless Hypermedia (i.e. href tags) drive application state5 6. A more lightweight way to buildservices (API) Using URLs to build on Web experience http://myservice.com/api/resources http://myservice.com/api/resources/{id} http://myservice.com/api/resources/{id}/relation HTTP verbs GET, POST, PUT, PATCH, DELETE Manage errors at the transport level6 7. Uniform Interfaces (HTTP Verbs)GETPOSTPUTPATCH Updates an existing resource (partially)DELETERetrieves a resourceGuaranteed not to cause side-effects (SAFE)Results are cacheableCreates a new resource (process state)Unsafe: effect of this verb isnt defined by HTTPUpdates an existing resourceUsed for resource creation when client knows URICan call N times, same thing will always happen (idempotent)Can call N times, same thing will always happen (idempotent)Removes a resourceCan call N times, same thing will always happen (idempotent) 8. Resources come from the businessdomain Task BoardSticky Notes8 9. Resources are nouns http://myservice.com/api/stickyNotes Verb: GET Action: Retrieves a list of sticky notes http://myservice.com/api/stickyNotes/12 Verb: GET Action: Retrieves a specific sticky note http://myservice.com/api/stickyNotes Verb: POST Action: Creates a new sticky note9 10. Resources are nouns http://myservice.com/api/stickyNotes/12 Verb: PUT Action: Updates sticky notes #12 http://myservice.com/api/stickyNotes/12 Verb: PATCH Action: Partially updates sticky note #12 http://myservice.com/api/stickyNotes/12 Verb: DELETE Action: Deletes sticky note #1210 11. Most so-calledRESTful APIs are notRESTful at alland thats not a bad thing at all 12. Rather, most RESTful APIs are reallyResource APIshttp://ServiceDesignPatterns.com/WebServiceAPIStyles/ResourceAPIagain, not a bad thing at all.Resource APIs totally rock !!! 13. REST Constraint ResourceAPIsClient/Server YesStateless Not requiredCacheable Responses Not required(Generic) Uniform Interface YesUnique URIs YesResources manipulated through Representations YesHypermedia as the Engine ofApplication StateNot requiredCopyright 2012 Rob Daigneau, All rights reserved 14. Stateless and cacheable response Resource APIs allow the use of cookies Cookies create session state that are partly storeon the client (user identification) and on the server(the state). Any response with a Set-Cookie header force the clientto send the cookie in every subsequent HTTP request Cookies interfere with cacheable response Any response with a Set-Cookie header should not becached, at least not the headers, since this caninterfere with user identification and create securityproblems 14 15. Hypermedia constraint Hypermedia as the Engine of ApplicationState (HATEOAS) Hypermedia constraint states that interaction withan endpoint should be defined within metadatareturned with the output (URL) Apply state transitions (at run time) by followinglinks Resource APIs allow URL to be known whencode is written, and not discover at run time15 16. Most so-called Web APIsare Resource APIshttp://en.wikipedia.org/wiki/Web_APIagain, not a bad thing at all.Web APIs totally rock !!! 17. 17Web APIs Best practices1. URL EndPoint Resources Version2. Message Body Content-Type3. Error handling HTTP Status Code4. Security5. Documentation 18. URL identifies a resource Endpoint name should be plural stickyNotes, collaborators Do not forget relations (business domain) GET /api/stickynotes/12/collaborators - Retrieves list ofcollaborators for sticky note #12 GET /api/stickynotes/12/collaborators/5 - Retrievescollaborator #5 for sticky note #12 POST /api/stickynotes/12/collaborators - Creates a newcollaborator in sticky note #12 PUT /api/stickynotes/12/collaborators/5 - Updatescollaborator #5 for sticky note #12 18 19. Verbs (actions) as resources Actions that don't fit into the world of CRUDoperations can be endpoint Change state with ToDo, InProgress or Doneaction Mark a sticky note in progress with PUT/stikyNotes/:id/inProgress GitHub's API star a gist with PUT /gists/:id/star unstar with DELETE /gists/:id/star19 20. Use Query to simplify resources Keep the base resource URLs lean byimplementing query parameters on top of thebase URL Result filtering, sorting & searching GET /api/stickyNotes?q=return&state=ToDo&sort=-priority,created_at Limiting which fields are returned by the API GET/api/stickyNotes?fields=id,subject,state,collaborator,updated_at&state=InProgress&sort=-updated_at20 21. Paginate using link headers Return a set of ready-made links so the APIconsumer doesn't have to construct linksthemselves The right way to include pagination detailstoday is using the Link header introduced byRFC 598821Link header:; rel="next",; rel="last" 22. Versioning Version via the URL, not via headers http://api.myservice.com/v1/stickynotes http://myservice.com/v1/stickynotes Benefits Simple implementation Ensure browser explorability Issues URL representing a resource is NOT stable acrossversions 22 23. Message (Content-type) JavaScript Object Notation (JSON) is thepreferred resource representation It is lighter than XML but as easy for humans toread and write No parsing is needed with JavaScript clients Requiring Content-Type JSON POST, PUT & PATCH requests should alsorequire the Content-Type header be set toapplication/json or throw a 415 UnsupportedMedia Type HTTP status code 23 24. Message (Content-type) A JSON object is an unordered set ofname/value pairs Squiggly brackets act as 'containers' Square brackets holds arrays Names and values are separated by a colon. Array elements are separated by commas24var myJSONObject ={ "web":[ { "name": "html", "years": "5" },{ "name": "css", "years": "3" }]"db":[ { "name": "sql", "years": "7" }]} 25. Message (Content-type) camelCase for field names Follow JavaScript naming conventions Do not pretty print by default Gzip by default Gzipping provided over 60% in bandwidth savings Always set the Accept-Encoding header25{customerData" : {"id" : 123, "name" : "John" }}Header:Accept-Encoding: gzip 26. Message (Post, Put and Patch) Updates & creation should return a resourcerepresentation To prevent an API consumer from having to hit theAPI again for an updated representation, have theAPI return the updated (or created) representationas part of the response In case of a POST that resulted in a creation, usea HTTP 201 status code and include a Locationheader that points to the URL of the new resource26 27. HTTP caching header Time-based (Last-Modified) When generating a request, include a HTTPheader Last-Modified if an inbound HTTP requests contains a If-Modified-Since header, the API should return a304 Not Modified status code instead of the outputrepresentation of the resource Content-based (ETag) This tag is useful when the last modified date isdifficult to determine27 28. HTTP Rate limiting header Include the following headers (using Twitter'snaming conventions as headers typically don'thave mid-word capitalization): X-Rate-Limit-Limit - The number of allowedrequests in the current period X-Rate-Limit-Remaining - The number ofremaining requests in the current period X-Rate-Limit-Reset - The number of seconds leftin the current period28 29. HTTP status codes 200 OK - Response to a successful GET, PUT, PATCH orDELETE. Can also be used for a POST that doesn't resultin a creation. 201 Created - Response to a POST that results in acreation. Should be combined with a Location headerpointing to the location of the new resource 204 No Content - Response to a successful request thatwon't be returning a body (like a DELETE request) 304 Not Modified - Used when HTTP caching headersare in play29 30. HTTP status codes 400 Bad Request - The server cannot or will not processthe request due to something that is perceived to be aclient error 401 Unauthorized - When no or invalid authenticationdetails are provided. Also useful to trigger an auth popupif the API is used from a browser 403 Forbidden - When authentication succeeded butauthenticated user doesn't have access to the resource 404 Not Found - When a non-existent resource isrequested 405 Method Not Allowed - When an HTTP method isn'tallowed for the authenticated user 30 31. HTTP status codes 409 Conflict - The request could not be completed due toa conflict with the current state of the resource 410 Gone - Indicates that the resource at this end point isno longer available. Useful as a blanket response for oldAPI versions 415 Unsupported Media Type - If incorrect content typewas provided as part of the request 422 Unprocessable Entity - Used for validation errors 429 Too Many Requests - When a request is rejected dueto rate limiting31 32. Security Encryption HTTPS (TLS) everywhere - all the time32 33. Security Authentication Never encode authentication on the URI Always identify the caller in the HTTP header Each request should come with authenticationcredentials Basic authentication over HTTPS33 34. Basic authentication over HTTPS Create a string with username and passwordin the form username:password Convert that string to a base64 encoded string Prepend the word Basic and a space to thatbase64 encoded string Set the HTTP requests Authorization headerwith the resulting string34Header:Authorization: Basic anNtaXRoOlBvcGNvcm4= 35. Security Autorization Return HTTP 403 Status Code if not authorized If necessity, use the body to provide more info35HTTP/1.1403ForbiddenContent-Type: application/json; charset=utf-8Server: Microsoft-IIS/7.0Date: Sat, 14 Jan 2012 04:00:08 GMTContent-Length: 251{code" : 123,description" : "You are not allowed to read this resource"} 36. Documentation An API is only as good as its documentation Docs should be easy to find http://myservice.com/api/help Docs should show examples of completerequest/response cycles Docs should provide error code HTTP 4xx and 5xx Status Code Error Code for HTTP 409 Status Code The holy grail for Web API is an auto-generated,always up-to-date, stylish documentation 36 37. Documentation37URI https://mysite.com:3911/api/members/{id}HTTP verb PUTParameters id : Card number of the member.Bodyname : Name of the member.email : Email adress of the member.langage : Langage used by member (Fr_CA ou En_US)Sample body{"name":"Mario Cardinal","email":[email protected]","language":"fr_CA"}SuccessResponseStatus Code: 204 No ContentError ResponseStatus Code: 400 Bad Request, Body: {"Error Code":"..."}Status Code: 401 Unauthenticated, see WWW-Authenticate value in headerStatus Code: 403 ForbiddenStatus Code: 404 Not FoundStatus Code: 429 Too Many Requests, see Retry-After value in headerStatus Code: 500 Internal Server ErrorStatus Code: 503 Service UnavailableError Code10: Inactive member20: Denied access member110: Database issues, Retry later 38. 38Do not hesitate to contact [email protected]@mario_cardinalQ & A