Upgrade to Pro — share decks privately, control downloads, hide ads and more …

TechTalks -002- Web API Design

TechTalks -002- Web API Design

Pragmatic REST interfaces with optimal benefit for app developers.

Pascal Polleunus

August 06, 2013
Tweet

Other Decks in Programming

Transcript

  1. Web  API  Design   Pragma0c  REST  interfaces   with  op0mal

     benefit   for  app  developers   Pascal  Polleunus  |  2013-­‐08-­‐06  
  2. Introduc0on   •  REST   – Architectural  style,  not  strict  standard

      – Flexibility  +  freedom  of  structure  =>  best  prac0ces   •  Design  approach   – Pragma0c  REST   – From  the  app  developer’s  POV   – Maximize  developer  produc1vity  and  success  
  3. Defini0on   •  Client/Server   •  Request/Response   •  Based

     on  HTTP   •  Resources  iden0fied  by  URLs   •  Stateless  
  4. Simple  and  intui0ve  URLs   •  2  base  URLS  per

     resource   •  Use  nouns,  not  verbs   – Use  plural  and  concrete  names   •  Non-­‐resource  URLs   – Use  verbs,  not  nouns   – Make  it  clear  in  your  documenta0on  
  5. URL  Structure   Scheme   h]ps   Domain   ://

      api.example.com   Base  URL   /   api   API  version   /   v1   Resource  name   /   books   Resource  ID   /   123   Rela1onship  name   /   authors   Data  format   .   json   Parameters   ?   foo=1&bar=abc   h]ps://api.example.com/api/v1/books/123/authors.json?foo=1&bar=abc  
  6. HTTP  verbs  as  CRUD   Resource   POST   Create

      GET   Read   PUT   Update   DELETE   Delete   Collec1on:   /books   Create  a  new  book   List  books   Bulk  update  books   Delete  all  books   Element  in  collec1on:   /books/123   Error   Show  Moby-­‐Dick   Update  Moby-­‐Dick   Delete  Moby-­‐Dick   Rela1onship:   /books/123/authors   Add  a  new  author   to  Moby-­‐Dick   Get  all  authors   of  Moby-­‐Dick   Bulk  update  all   rela0onships   Delete  the   rela0onship  
  7. Requests   •  URL  &  Method  (HTTP  verb)   • 

    Headers   – Content-­‐Type:  applica0on/json;  charset=ug-­‐8   – Accept:  applica0on/json   •  Body   – Data  to  submit   •  forma]ed  as  defined  in  Content-­‐Type  
  8. Request  –  Example  POST   POST  h]ps://api.example.com/api/v1/books.json   Content-­‐Type:  applica0on/json;

     charset=ug-­‐8     {! "title": "Moby-Dick",! "isbn": "978-0393972832",! "publishingDate": "1999-07-27",! "numPages": 752,! "available": true,! "authorUri": "api/v1/authors/herman-melville",! "publisherUri": "api/v1/publishers/0123456789abcdef0123456789abcdef"! }!
  9. Requests  –  Behind  the  ?   •  Keep  the  URLs

     intui0ve  and  simple   •  Put  op0onal  parameters  behind  the  ?   – Par0al  response:  fields=id,0tle,reviews.author.name   – Pagina0on:  limit=25&offset=50   – Search:  q=foo+bar   – Misc:     •  pre]y=true  
  10. Responses  –  Success   •  Status  code  —  Success  

    –  200  OK:   •  for  GET  requests,  the  resource  was  successfully  retrieved.   •  for  POST  requests  which  perform  other  ac0ons  than  crea0ng  a   resource,  the  opera0on  was  successful.   •  for  PUT  requests,  the  resource  was  successfully  updated.   •  for  DELETE  requests,  the  resource  was  successfully  deleted.   –  201  Created:   •  POST  requests  which  create  a  resource  will  return  this  when  the   opera0on  was  successful.  It  will  also  contain  a  `Loca0on`  header   providing  the  URL  of  the  created  resource.   –  204  No  Content:   •  PUT  requests  which  update  a  resource  will  return  this  when  the   opera0on  was  successful.  
  11. Responses  –  Error   •  Status  code  —  Error  

    –  400  Bad  Request   •  Your  request  is  not  well-­‐formed  or  contains  errors.  The  response  body   contains  details  of  the  error.   –  401  Unauthorized   •  You  a]empt  to  authen0cate  with  an  invalid  API  key.   –  403  Forbidden   •  You  a]empt  to  retrieve  content  you  don't  have  access  to  or  to  perform  an   ac0on  you're  not  allowed  to.   –  404  Not  Found   •  You  a]empt  to  request  a  resource  which  doesn't  exist.   –  500  Internal  Server  Error   •  An  unhandled  error  occurs  on  the  API  server  for  some  reason.   –  501  Not  Implemented   •  The  ac0on  you're  trying  to  perform  is  not  supported.  
  12. Responses   •  Headers   – Content-­‐Type:  applica0on/json;  charset=ug-­‐8   – Loca0on:

     h]ps://api.example.com/api/v1/resource/id   •  Body   – forma]ed  as  defined  in  Content-­‐Type   – Elements:  meta  +  object   – Collec0ons:  meta  +  objects   •  totalCount,  limit,  offset,  previous,  next  
  13. Response  –  Example  POST   POST  h]ps://api.example.com/api/v1/books.json     HTTP/1.1

     201  CREATED   Content-­‐Type:  applica0on/json;  charset=ug-­‐8   Loca0on:  h]ps://api.example.com/api/v1/books/978-­‐0393972832  
  14. Response  –  Example  GET   GET  h]ps://api.example.com/api/v1/books/978-­‐0393972832.json   Content-­‐Type:  applica0on/json;

     charset=ug-­‐8     {! "meta": {! "responseCode": 200,! ...! },! "object": {! "uri": "api/v1/books/978-0393972832",! "id": "978-0393972832",! "title": "Moby-Dick",! "isbn": "978-0393972832",! "publishingDate": "1999-07-27",! "numPages": 752,! "available": true,! "authorUri": "api/v1/author/herman-melville",! "publisherUri": "api/v1/publisher/0123456789abcdef0123456789abcdef"! }! }!
  15. Response  –  Example  GET  List   GET  h]ps://api.example.com/api/v1/books.json?limit=10&offset=50   Content-­‐Type:

     applica0on/json;  charset=ug-­‐8     {! "meta": {! "totalCount": 120,! "limit": 10,! "offset": 50,! "previous": "api/v1/books.json?limit=10&offset=40",! "next": "api/v1/books.json?limit=10&offset=60"! },! "objects": [! {! "uri": "api/v1/books/978-0393972832",! "id": "978-0393972832",! "title": "Moby-Dick",! ...! },! { ... }! ]! }!
  16. Errors   •  HTTP  status  code  +  body:   – 

    errorCode:  Error  code   •  Numbering  starts  at  1000  =>  ≠  HTTP  status  codes   –  errorType:  Error  type  (excep0on-­‐like)   –  errorDoc:  Link  to  the  error  documenta0on   –  developerMessage:  Verbose,  plain  language  descrip0on  of   the  problem  for  the  app  developer  with  hints  about  how  to  fix  it   –  userMessage:  Message  that  can  be  passed  to  the  app  user   –  userDetailedMessages:  Detailed  info  about  each  error  
  17. Input  &  Output   •  Formats:  JSON,  XML,  YAML,  HTML,

     p-­‐list   –  Input  in  body:   •  Content-­‐Type  header   •  Payload  must  comply   –  Input  via  query  string:  URL-­‐encoded   •  Dates  &  0mes:   –  Date:  "2013-­‐12-­‐31"   –  Time:  "23:59:59"   •  with  seconds  frac0on:  "23:59:59.123"   •  with  0mezone:  "23:59:59+01:00"  (UTC:  "23:59:59Z")   –  Date/0me:  "2013-­‐12-­‐31T23:59:59"   –  Full  date/0me:  "2013-­‐12-­‐31T23:59:59.123+01:00"  
  18. IDs  &  Naming   •  IDs  as:   – UUID  (v4):

     f47ac10b-­‐58cc-­‐4372-­‐a567-­‐0e02b2c3d479   – Slug:  lower-­‐case-­‐dash-­‐separated-­‐unique-­‐name   •  URL  parameters   – lower-­‐case-­‐dash-­‐separated   •  Response  names   – JSON:  JavaScript  conven0ons:  camelCase   – XML:  snake_case  
  19. Excep0onal  Behaviors   •  No  HTTP  status  code   – ?suppress-­‐response-­‐codes=true

      – HTTP  status  code  is  always  200   – responseCode  in  body  (meta)   •  Restricted  HTTP  methods   – ?method=put   – HTTP  method  is  always  GET   – /!\  post  and  delete  =  dangerous  via  GET  requests  
  20. Authen0ca0on   •  Use  standards   •  Op0ons:   – OAuth

      – API  Key:  username  +  API  key   – HTTP  Digest  Auth:  username  +  hashed  password   – HTTP  Basic  Auth:  username  +  password  
  21. Summary   •  Keep  simple  things  simple   •  Imagine

     how  developers  will  use  your  API   •  Be  complete  and  RESTful,  then  provide   shortcuts   •  Take  advantage  of  par0al  response  syntax   •  Well-­‐documented,  with  code  samples   •  Complement  with  an  SDK  
  22. API  Façade  Pa]ern   1.  Design  the  ideal  API  

    –  design  the  URLs,  request  parameters  and  responses,   payloads,  headers,  query  parameters,  and  so  on   –  the  API  design  should  be  self-­‐consistent   2.  Implement  the  design  with  data  stubs.   –  allows  app  developers  to  use  your  API  and  give  you   feedback  even  before  your  API  is  connected  to   internal  systems   3.  Mediate  or  integrate  between  the  façade  and   the  systems  
  23. Inspira0on   •  API   –  Foursquare:  h]ps://developer.foursquare.com/   – 

    GitHub:  h]p://developer.github.com/   –  Instagram:  h]p://instagram.com/developer/   –  Twillio:  h]p://www.twilio.com/docs/api/rest   –  Twi]er:  h]ps://dev.twi]er.com/docs/api   •  SDK   –  Yahoo:  h]p://developer.yahoo.com/social/sdk/   –  Paypal:  h]p://paypal.github.io/   •  Documenta0on   –  Campaign  Monitor:  h]p://www.campaignmonitor.com/api/   –  Swagger:  h]p://developer.wordnik.com/docs.html  
  24. References   •  Hypertext  Transfer  Protocol  –  HTTP/1.1   – 

    h]p://www.ieg.org/rfc/rfc2616.txt   •  List  of  HTTP  status  codes   –  h]p://en.wikipedia.org/wiki/List_of_HTTP_status_codes   •  ISO  8601  (Data  elements  and  interchange  formats)   –  h]p://en.wikipedia.org/wiki/ISO_8601   •  ECMA-­‐262  (ECMAScript  scrip0ng  language)   –  h]p://en.wikipedia.org/wiki/ECMA-­‐262  
  25. Resources   •  Apigee:  API  Best  Prac0ces   –  h]p://apigee.com/about/api-­‐best-­‐prac0ces

      •  REST  worst  prac0ces  (2008-­‐11-­‐14)   –  h]p://jacobian.org/wri0ng/rest-­‐worst-­‐prac0ces/   •  Richardson  Maturity  Model  (2010-­‐03-­‐18)   –  h]p://mar0nfowler.com/ar0cles/richardsonMaturityModel.html   •  Designing  Hypermedia  APIs  (2012)   –  h]p://www.designinghypermediaapis.com/   •  REST  API  Documenta0on  (2012-­‐08-­‐06)   –  h]p://mestachs.wordpress.com/2012/08/06/rest-­‐api-­‐documenta0on/