O slideshow foi denunciado.
Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.

Creating Truly RESTful APIs

16.371 visualizações

Publicada em

A very short presentation on the basics of REST, and how to design APIs to be RESTful

Publicada em: Tecnologia

Creating Truly RESTful APIs

  2. 2. A STORY IN THREE PARTS1. URLs = Resources; Verbs = Actions2. Using the HTTP Machinery3. Linking
  4. 4. RESOURCE ARCHETYPES: DOCUMENT Think “object instance” or “database record.” Examples:  /partnerships/1234  /partnerships/1234/funds/ABCD  /users/0987  /users/0987/settings Typical verbs:  GET — retrieves the document  DELETE — deletes the document  PATCH — performs a partial update of the document  PUT — creates or updates the document (see upcoming slides) Documents can be organized into either collections or stores
  5. 5. RESOURCE ARCHETYPES: COLLECTION A server-managed resource directory Clients may propose addition to the directory, but the server decides the result Examples:  /partnerships  /partnerships/1234/funds  /users Typical verbs:  GET /collection — a listing of the whole collection, either inline or as links  POST /collection — creates a new document, and returns you a link to it  PUT /collection/document — replaces an existing document  GET, PATCH, DELETE /collection/document
  6. 6. RESOURCE ARCHETYPES: STORE A client-managed resource repository Examples:  /users/0987/favorite-funds  /partnerships/1234/metadata Documents exist under stores:  /users/0987/favorite-funds/ABCD  /partnerships/1234/metadata/investment-preferences Typical verbs:  GET /store — a listing of the whole store, either inline or as links  PUT /store/document — creates or replaces the document  GET, PATCH, DELETE /store/document
  7. 7. DOMAIN MODELING WITH RESOURCES URLs are always nouns, never actions:  Find distance between points: GET /distance?point1=x&point2=y  Discount this item’s price by 15%:  PUT /item/discount { percent: 15 }  or PUT /discounts/itemID { percent: 15 } if discounts are a primary entity in your domain Hierarchical URL structure represents hierarchy of resources in your domain  Not just stores and collections: /user/0987/settings; /user/0987/pictures/large; etc. Query parameters represent filtering, sorting, and projections Extra verbs:  HEAD lets you interrogate for certain metadata, e.g. Content-Length  OPTIONS lets you find out what verbs are supported, e.g. “is this document deletable?”
  9. 9. STATUS CODES: THE BASICS There’s life beyond 200, 404, and 500!  100, 101 = meta stuff; don’t worry about it  2xx = success  3xx = redirection: further action may be needed  4xx = client error: user screwed up  5xx = server error: server screwed uphttp://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  10. 10. SAMPLE SIMPLE STATUS CODE USES: GET AND DELETE GET /partnerships/1234/funds/ABCD  200 OK  301 Moved Permanently: the fund has been transferred to another partnership  401 Unauthorized: you need to authenticate first  403 Forbidden: you’re authenticated, but not authorized  404 Not Found: no such fund exists under this partnership DELETE /document  204 No Content
  11. 11. SAMPLE SIMPLE STATUS CODE USES: PUT AND POST PUT /store/document  200 OK: old document overwritten  201 Created: new document created  409 Conflict: you tried to overwrite the document but you didn’t have the latest version POST /collection  201 Created: new document created  303 See Other: a document with that name (or whatever) already existed Either case:  400 Bad Request: data did not pass validation  401, 403: as before  413 Request Entity Too Large: you tried to upload too large of a document  415 Unsupported Media Type: you tried to upload a PDF, but we only support text files
  12. 12. OTHER IMPORTANT MACHINERY Caching  Client-side caching via Cache-Control and Expires headers  Conditional GETs to avoid downloading again Conditional updates to avoid conflicts Content negotiation to serve the correct representation of a resource Range requests for downloading chunks from a larger document Metadata headers: Content-Type, Content-Length, Etag, … Authorization headerTakeaway: no need to build envelopes or protocols on top of HTTP; it has the tools you need
  13. 13. LINKING
  14. 14. HYPERTEXT AS THE ENGINE OF APPLICATION STATE Your API should advertise a single entry point, e.g. https://api.lab49.com From there, links direct you to desired resources Links are specified by relationship types, or rels.  There are standard rels, e.g. prev, next, parent, self, etc.  But most relationships are domain-specific, telling you how to get to an interesting resource Clients do not know resource URLs  They know the single entry point URL  They know the rels of resources they are interested in  They know how to navigate from resource to resource
  15. 15. EXAMPLE: GET /{ "_links": { "http://rels.api.lab49.com/partnerships": { "href": "/partnerships" }, "http://rels.api.lab49.com/users": { "href": "/users" } }}
  16. 16. EXAMPLE: GET /PARTNERSHIPS{ "_links": { "http://rels.api.lab49.com/partnership": [ { "href": "/partnerships/1234" }, { "href": "/partnerships/4321" }, { "href": "/partnerships/3142" } ] }}
  17. 17. EXAMPLE: GET /PARTNERSHIPS/1234{ "_links": { "http://rels.api.lab49.com/funds": { "href": "/partnerships/1234/funds" } }, "name": "Denicola Global Management", "type": "GP", "missionStatement": "To make lots of money"}
  18. 18. WRAP-UP
  19. 19. THINGS WE DON’T HAVE TIME FOR Controller resources Embedded resources API versioning schemes Authentication, e.g. with OAuth 2 Data formats, e.g. how to format PATCH data or hypermedia links Playing nice with proxies HTTPbis
  20. 20. THINGS YOU SHOULD READ HTTPbis: Semantics and Content (and the others) RESTful Web Services Cookbook by Subbu Allamaraju REST API Design Rulebook by Mark Masse Hypertext Application Language (HAL) spec