How RESTful Is Your REST?

4,480 views
4,358 views

Published on

The rise of Mobile and the diversity its technologies make exposing a RESTfull API the most crucial capability of any application and the key to its success. In the absence of widely adopted best practices and well-defined conventions, designing such an API is nothing but trivial. This presentation introduces the fundamentals of REST architecture, and discusses the principles of RESTfull design. Among the topics covered: resource modeling (URI design, and HTTP verbs/status code canonical usage), multiple representation support, testing, cache control, security (Http and OAuth), and API versioning. HATEOAS and REST maturity model are also discussed. No prior knowledge REST is required.

Published in: Technology
0 Comments
16 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
4,480
On SlideShare
0
From Embeds
0
Number of Embeds
729
Actions
Shares
0
Downloads
120
Comments
0
Likes
16
Embeds 0
No embeds

No notes for slide
  • http://translate.google.com/#sv/en/Trevligt%20att%20träffa%20dig%20svenska%20hackare!http://translate.google.com/#en/sv/I%20am%20happy%20to%20be%20here
  • How RESTful Is Your REST?

    1. 1. How Restful is Your Rest? Abdelmonaim Remani @PolymathicCoder Øredev 2012 Malmö, Sweden
    2. 2. LicenseCreative Commons Attribution Non-Commercial 3.0 Unported http://creativecommons.org/licenses/by-nc/3.0Disclaimer: The graphics, logos, and trademarks used this presentationbelong to their rightful owners.
    3. 3. Trevligt att träffa dig nordisk hackare!
    4. 4. About MeSoftware Architect at Just.me Inc.Interested in technology evangelism and enterprise softwaredevelopment and architectureFrequent speaker (JavaOne, JAX, OSCON, OREDEV, etc…)Open-source advocatePresident and founder of a number of user groups NorCal Java User Group The Silicon Valley Spring User Group The Silicon Valley Dart MeetupBio: http://about.me/PolymathicCoderTwitter: @PolymathicCoderEmail: abdelmonaim.remani@gmail.com
    5. 5. Let’s Get Started!
    6. 6. What is an API?Application Programming InterfaceYou have an API when (All or a part of) the functionality of your system is exposed In the form a well-defined interface (or a collection of interfaces) of services That are externally accessible And programmatically consumable through to a well-defined protocolYou have a Web API when The functionality of your system is exposed In the form of a collection of Web Services That are publicly addressable through a set of Web endpoints (URLs) And programmatically consumable though HTTP protocol
    7. 7. Why Bother?Web 2.0 Convenience and standardization around accessing data and servicesExplosion of Open APIs Location-Based (Maps, Geo-coding, Weather, Traffic, Etc…) Financial Data Social Data Government Data, NGOs, etc… Etc…
    8. 8. Why Bother?The birth of Mashups (Hybrid Web Applications) Combines services to create a value-added Aggregate and visualize data in interesting waysSpoiled user-base that demands a lot more than whata single service can offer I want to see the closest Moroccan restaurants to my current location on a map along with consumer ratings and whether any of my friends has recently checked-in in the last 30 days
    9. 9. Why Bother?Mobile A lot more apps than browsers Mobile traffic is diminishing web traffic exponentiallyMashups 2.0 is Mobile
    10. 10. Why Bother?You goal behind exposing a Web API should be for yourservices to be mashed up with others Beneficial Will drive traffic in your direction Will allow you to learn about your own services and how they are being used Will create goodwill with new potential usersImplies The majority of the traffic is NOT going to be through your own app or website Your App is the API it exposes
    11. 11. ChallengesYou have very little control on how your API will beused You do not control how your services are orchestrated (Used in combination)Public APIs are forever Better get it right the first time!
    12. 12. What’s Right?How does a good API feel like? Easy to learn and use Intuitive POLA (Principle of Least Astonishment) Consistent Based on standards Adheres to a convention Hard to misuse Well-Documented
    13. 13. What is REST?
    14. 14. What is REST?REpresentational State TransferRoy Fielding Dissertation (Chapter 5-6) Architectural Styles and the Design of Network-based Software Architectures http://www.ics.uci.edu/~fielding/pubs/dissertation/top.h tm
    15. 15. What is REST about?Goals Scalability Generality of Interface Independent Deployment of Component Intermediary ComponentsRest Constraints Client-Server Stateless Conversion Cacheable Uniform Interface Layered System Code on-demand (Optional)
    16. 16. What is REST about?Leveraging the web as a platform Resource-Oriented Anything exposed on the web is a resource (Documents, video, device, etc…) Resources are identifiable and addressable by URIsAn architecture based on the HTTP protocol
    17. 17. API Design
    18. 18. Richardson Maturity ModelLeonard Richardson http://www.crummy.com/writing/speaking/2008-Qcon/
    19. 19. The Address Book
    20. 20. The Address BookA Simple address book that allows users to manage their contact dataA user has a username and is associated with a set of contactsA contact is constitute of: a unique ID, a name, and a phone numberUser Stories: As a user, I want to add a contact to my address book As a user, I want to list all contacts in my address book As a user, I want to view a specific contact in my address book As a user, I want to modify a specific contact in my address book As a user, I want to delete a specific contact from my address book As a user, I want to email a specific contact in my address book to a friend
    21. 21. Richardson Maturity Model Level 0Single URI Identify all possible operations/functionality indicate the desired operation in the payloadSingle HTTP Verb
    22. 22. The Address Book at Level 0SOAP-Based RPC Web Service Endpoint http://www.polymathiccoder.com:9999/ws/addressbook WSDL http://www. polymathiccoder.com:9999/ws/addressbook?wsdl addContact(“bob”, “Abdel Remani”, “(123) 123-1234”) lookupAllContacts(“bob”) lookupContactById(“bob”, 123) editContact(“bob”, 123, “Abdelmonaim Remani”, “(123) 123- 1234”) deleteContact(“bob”, 123) emailContact(“bob”, 123, “sandy@polymathiccoder.com”) markAsFavorite(“bob”, 123)
    23. 23. Richardson Maturity Model Level 1Multiple URLs One URL per method URI encoded operationsSingle Verb GET is used to change stage GET should be safe or idempotent
    24. 24. The Address Book at Level 1URL Tunneling Endpoints http://www. polymathiccoder.com/addressbook/add- contact?user=bob&name=Abdel%20Remani&phone- number=(123)%20123-1234 http://www. polymathiccoder.com/addressbook/lookup-all- contacts?user=bob http://www. polymathiccoder.com/addressbook/lookup- contact?user=bob&id=123 http://www. polymathiccoder.com/addressbook/edit- contact?user=bob&id=123&name=Abdelmonaim%20Remani&phone- number=(123)%20123-1234 http://www. polymathiccoder.com/addressbook/delete- contact?user=bob&id=123 http://www. polymathiccoder.com/addressbook/email?user=bob&id=123&to=sand y@polymathiccoder.com http://www. polymathiccoder.com/addressbook/mark-as-
    25. 25. Richardson Maturity Model Level 2Level 2 Many URI Leverage multiple HTTP VerbsYou might call yourself Restful at this point Creating a uniform interface based on the HTTP protocol
    26. 26. The Address Book at Level 2 The Restful Address Book
    27. 27. Recourse IdentificationFind all the nouns in users stories
    28. 28. Recourse IdentificationHere are all the nouns we found: User Uniquely identifiable by a username Contact Uniquely identifiable by an idLet’s start calling nouns resources
    29. 29. Recourse IdentificationResources are identifiable and addressable by URIs The collection of resources the same kind Users /users Contacts /contacts The individual resources within its collections The User whose username is “abdel” /users/abdel The Contact whose ID is “123” /contacts/123
    30. 30. Recourse IdentificationIs there association between any of our resources? User has many Contacts A User can is the parent resource of a ContactChaining resources together “/” in a URI implies hierarchy Contact whose id is “123” and owner is the User whose username is “abdel” /users/abdel/contacts/123
    31. 31. Recourse IdentificationWe end with 2 URIs referring to the same Contactresource whose ID is “123” /contcats/123 /users/abdel/contacts/123We ask the question: Can a “Contact” recourse existindependently from “User” resource? The Answer is NO in this case /contcats/123 /users/abdel/contacts/123
    32. 32. Leveraging HTTP VerbsUser Stories:
    33. 33. Leveraging HTTP VerbsCRUD Operations map to HTTP Verbs GET for Read POST for Create PUT for Update DELETE for Delete
    34. 34. Leveraging HTTP VerbsTo view all Abdel’s contacts GET /users/abdel/contactsTo view Abdel’s contact whose ID is 123 GET /users/abdel/contacts/123To add a new contact to Abdel’s address book POST /users/abdel/contactsTo update Abdel’s contact whose is ID is 123 PUT /users/abdel/contacts/123To delete Abdel’s contact whose is ID is 123 DELETE /users/abdel/contacts/123
    35. 35. Non-CRUDNon-CRUD operations do not map to HTTP verbs Use descriptive verbs in URLs as Controller callsTo email Abdel’s contact whose ID is 123 tosandy@polymathiccoder.com GET /users/abdel/contacts/123/email?to=sandy@polymathicc oder.comTo mark Abdel’s contact whose ID is 123 tosandy@polymathiccoder.com PUT /users/abdel/contacts/123/mark-as-favorite
    36. 36. The Opinion Shop: URLsConvention for your URLs RFC 3986: URLs are case sensitive No CAPS to avoid confusion No camel-case Links are usually underlined Use Hyphens instead of Underscores for readability
    37. 37. Resource RepresentationFor a resource identified by the same URI Representation in the form of MIME/Media Types Multiple data representation is supported Use “Accept” HTTP Header Avoid file extensions Manipulation is supported through multiple data representation Use “Content-Type” HTTP Header
    38. 38. The Opinion Shop: URLsConvention object names in payload No JavaScript Convention http://javascript.crockford.com/code.html No camel-case I prefer using using Hyphens to be consistent with URLs
    39. 39. Leveraging HTTP Status Codes1xx: Informational2xx: Success3xx: Redirection4xx: Client Error5xx: Server Error
    40. 40. Leveraging HTTP Status Codes200 – OK Success Error with details in the body201 – Created202 – Accepted400 – Bad Request401 – Unauthorized403 – Forbidden404 – Not Found405 – Method Not Allowed406 – Not Acceptable409 – Conflict412 – Precondition Failed415 – Unsupported Media Type500 – Server Problems
    41. 41. Richardson Maturity Model Level 4HATEOAS Hypermedia As The Engine Of Application SateBusiness Workflow Capturing the different states of a resource Transitions EndpointReturning all possible links given the current state ofthe resource
    42. 42. Partials and Variations
    43. 43. PaginationUse Query ParametersPagination Don’t do this /page/1 Inspired by SQL ?limit=20&offset=20 Inspired by RFC 5005: Feed Paging and Archiving http://tools.ietf.org/html/rfc5005 ?next=20&to-item=6783&inclusive=true ?prev=23&to-item=6783&inclusive=false
    44. 44. Ordering, Sorting and FiteringUse Query ParametersOrdering and Sorting ?order-by=populatrity&sorted-as=desc ?order-by=first-name&sorted-as=ascFiltering ?filter-by= Etc…
    45. 45. ViewsSupport custom views of the data at the schema level Use an easy expression language ?fields=(first-name,phone-number) ?fields=!(last-name) Google, LinkedIn, and others use a variationsSupport different predefined views of the data Use ?view=brief ?view=full
    46. 46. Legacy Clients
    47. 47. Legacy ClientsOlder Clients Only support GET and POST HTTP MethodsUse ?method=put
    48. 48. Security
    49. 49. SecurityRemember that your Web Services must be stateless Do not use cookies or HTTP session under any circumstances The client must send credentials to autenticate with very callOptions HTTP Security Preemptively Setting “Authorization” HTTP Header Basic or Digest OAuth
    50. 50. Testing You API
    51. 51. TestingSpring RestTemplate http://static.springsource.org/spring/docs/3.1.x/spring- framework-reference/html/remoting.html#rest- resttemplateJayway’s Rest-Assured http://code.google.com/p/rest-assured/
    52. 52. Versioning
    53. 53. VersioningDon’t do this /api/v1/… ?v=1 /api/v1.1/… /api/07-19-2012/…Use HTTP Headers Use Vendor-Specific MIME/Media Types Accept application/vnd.polymathiccoder.addressbook+json
    54. 54. Documentation
    55. 55. DocumentationWhat to document Endpoint Description Prerequisites Request Response
    56. 56. DocumentationWhat to document Use a mind map
    57. 57. DocumentationRefer to other’s documentations Twitter, Facebook, Google, etc…ioDocs from Mashery http://www.mashery.com/product/io-docs Live Example: http://developer.rottentomatoes.com/iodocs
    58. 58. How Restful Is REST?
    59. 59. How Restful Is Your REST?Richardson Maturity Model as a reference It’ll tell where you standHow Restful do you want to be?Dogmatic vs. PragmaticIn Common Law, there is this concept of “The ReasonableMan” Being reasonable is relative Look in similar situation Similar expertise Custom and usage
    60. 60. Question?
    61. 61. Recommended Reading
    62. 62. Tack själv!PolymathicCoder

    ×