APIs REST UsablesJavier Ramírez@supercoco9@aspgems
APIs REST                                           usableS*                                                      edición ...
1996
1995
1996
1994
2001
La usabilidad Web es un  enfoque para construirsitios web faciles de usar            para un usuario final, sin que se req...
LearnabilityEfficIeNcyMemorabiliTyErrorsSatisfActiOn
API “REST”Hecha con RAILS  en lo que se TARDA EN decir  constantinopla
separation of concerns
modelo de                         recursos                 Autenticación y                      (NO) Estado               ...
BASIC ACCESS AUTHENTICATION authenticate_or_request_with_http_basic do |login, password|   User.find_by_login_and_password...
SUCCESS consistently       fail consistently
huddle twitter                                     200 OK 200       OK     Success!                   201 Created 304     ...
Accept: application/vnd.aspgems.invoicefu.v1.xml   THE ACCEPT HEADERHTTP/REST Standard        Not everyone          Less o...
REST explicado por un señorque tan listo no será cuando        no usa gafasclient-server,stateless,layered,cacheableResour...
INTERFAZ UNIFORME get, HEAD, TRACE,      OPTIONSpost, put*, delete*,      PATCH**fallbacks para clientes viejos oincompletos
here   bedragons
restfest 2011
expose ONLY      WHAT ISStrictly necessary
resources are not models
Aggregation/ composition               Multiple           representations
HypermediaAPIs descubriblesRecursos asociadosSiguientes pasosPaginación
https://invoicefu.com?     format=xml
curl -X POST "https://invoicefu.com/api/session?format=xml&login=hello@invoicefu.com&password=YAY  <?xml version="1.0" enc...
Rob Eisenberg<productions> <links>  <link rel="self" href="..." />  <link rel="next" href="..." /> </links> <production>  ...
Mike Kelly{ "_links": {   "self": { "href": "..." } }, "title": "Real World ASP.NET MVC3", "description": "In this advance...
DARREL MILLER{    "_links" : {    "self" : { "href" : "/user/95/allproductions" },    },    "name" : "Joe",    "_embedded"...
ACTS AS API :Filtros
URI templateshttp://example.com/~{username}/http://example.com/dictionary/{term:1}/{term}http://example.com/search{?q,lang}
> curl "https://invoicefu.com/api/accounts/108-cole-mertz-fake/invoices/new?api_key=ddd349b30b6d9fde97b01b827e6be5ed1e4fbe...
templates        for new       resources> curl "https://invoicefu.com/api/accounts/108-cole-mertz-fake/invoices/new?api_ke...
Multiple consumers
All your FORMATare belong to us*even native formats
javascript revival
Cross originresource sharing
use the                    metadata                         lukePermitir cabeceras del tipo    return-async    return-repr...
Respuestas parcialeshttps://gdata.youtube.com/feeds/api/users/default/uploads?fields=entry(title,gd:comments,yt:statistics...
Implementación en invoicefu
apigee
http://usemyapi.com 12 mayo 2012
APIs REST                                           usableS*                                                      edición ...
APIs REST Usables con Hypermedia por Javier Ramirez, para codemotion
APIs REST Usables con Hypermedia por Javier Ramirez, para codemotion
APIs REST Usables con Hypermedia por Javier Ramirez, para codemotion
APIs REST Usables con Hypermedia por Javier Ramirez, para codemotion
APIs REST Usables con Hypermedia por Javier Ramirez, para codemotion
APIs REST Usables con Hypermedia por Javier Ramirez, para codemotion
APIs REST Usables con Hypermedia por Javier Ramirez, para codemotion
APIs REST Usables con Hypermedia por Javier Ramirez, para codemotion
APIs REST Usables con Hypermedia por Javier Ramirez, para codemotion
APIs REST Usables con Hypermedia por Javier Ramirez, para codemotion
APIs REST Usables con Hypermedia por Javier Ramirez, para codemotion
Upcoming SlideShare
Loading in …5
×

APIs REST Usables con Hypermedia por Javier Ramirez, para codemotion

3,060 views
2,968 views

Published on

Con la adopción de REST, la proliferación de smartphones y tablets y el revival del JavaScript, exponer nuestra aplicación como un servicio es más importante que nunca.

Frameworks como Rails hacen muy fácil la creación de un API (más o menos) REST, pero en muchas ocasiones estas APIs se diseñan sin pensar realmente en los desarrolladores que las va a usar.

En esta charla habo sobre algunos de los puntos que pueden hacer tu API REST más amigable para desarrolladores, cubriendo áreas como el autodescubrimiento, autenticación, cabeceras, formatos, versionado, parámetros, documentación y herramientas.

Aunque comparte tema (y algunas slides) con la charla de APIs usables que preparé para el grupo de Usuarios de Ruby en Londres, gran parte del material es inédito.

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

No Downloads
Views
Total views
3,060
On SlideShare
0
From Embeds
0
Number of Embeds
110
Actions
Shares
0
Downloads
44
Comments
0
Likes
7
Embeds 0
No embeds

No notes for slide

APIs REST Usables con Hypermedia por Javier Ramirez, para codemotion

  1. 1. APIs REST UsablesJavier Ramírez@supercoco9@aspgems
  2. 2. APIs REST usableS* edición codemotion.es{"links":[ {"rel":"author", "uri":"http://javier-ramirez.com"}, {"rel":"work", "uri":"http://aspgems.com"}, {"rel":"twittEr", "uri":"http//twitter.com/supercoco9"} {"rel":"api-usable", "uri":"https//invoicefu.com"}]}*ningún gatico (ni ningún friki ansioso) ha sido dañado para hacer esta presentación
  3. 3. 1996
  4. 4. 1995
  5. 5. 1996
  6. 6. 1994
  7. 7. 2001
  8. 8. La usabilidad Web es un enfoque para construirsitios web faciles de usar para un usuario final, sin que se requiera ninguna formacion especializada
  9. 9. LearnabilityEfficIeNcyMemorabiliTyErrorsSatisfActiOn
  10. 10. API “REST”Hecha con RAILS en lo que se TARDA EN decir constantinopla
  11. 11. separation of concerns
  12. 12. modelo de recursos Autenticación y (NO) Estado formatosEstados y gestión versionadode errores múltiplesanalítica consumidoresmonetización paginaciónDocumentación Escalabilidadfirst class api? cuotas metadatos… y uSaBiLidAd cachés
  13. 13. BASIC ACCESS AUTHENTICATION authenticate_or_request_with_http_basic do |login, password| User.find_by_login_and_password login, password endUser and password must be passed every timeTOKENDigest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )User.find_by_login_and_api_key( params[:login], params[:api_key] )Client can send it as a parameter or as a headerOAUTHDepends on third party librariesRequires initial registration of client and more integration
  14. 14. SUCCESS consistently fail consistently
  15. 15. huddle twitter 200 OK 200 OK Success! 201 Created 304 Not Modified 202 Accepted 400 Bad Request 400 Bad Request 401 Unauthorized 401 403 Forbidden Unauthorized 404 Not Found 403 Forbidden 406 Not Acceptable 404 Not Found 420 Enhance Your Calm 410 Gone invoicefu 500 Internal Server 200 OK Success! Error 201 Created 502 Bad Gateway 304 Not Modified 503 Service Unavailable 401 Unauthorized 404 Not FoundUseful Status 422 Unprocessable Entity429 Too many requests 406 Not Acceptable204 No Content 500 Internal Server Error
  16. 16. Accept: application/vnd.aspgems.invoicefu.v1.xml THE ACCEPT HEADERHTTP/REST Standard Not everyone Less obviousUnambiguous supports headers Harder to useResources != or custom types. Non standard content-Representations Generic content typesVersion as you need it types are Skips HTTP server logs preferred
  17. 17. REST explicado por un señorque tan listo no será cuando no usa gafasclient-server,stateless,layered,cacheableResources Resource Identifiers Resource metadataUniform interface operations Representations Representation metadataHATEOASOptionally: code on demand señor sin gafas
  18. 18. INTERFAZ UNIFORME get, HEAD, TRACE, OPTIONSpost, put*, delete*, PATCH**fallbacks para clientes viejos oincompletos
  19. 19. here bedragons
  20. 20. restfest 2011
  21. 21. expose ONLY WHAT ISStrictly necessary
  22. 22. resources are not models
  23. 23. Aggregation/ composition Multiple representations
  24. 24. HypermediaAPIs descubriblesRecursos asociadosSiguientes pasosPaginación
  25. 25. https://invoicefu.com? format=xml
  26. 26. curl -X POST "https://invoicefu.com/api/session?format=xml&login=hello@invoicefu.com&password=YAY <?xml version="1.0" encoding="UTF-8"?> <user> <id>3</id> <name>javier ramir</name> <email>javier@formatinternet.com</email> <locale>es</locale> <twitter-nickname>supercoco9</twitter-nickname> <facebook-uid nil="true"></facebook-uid> <facebook-nickname nil="true"></facebook-nickname> <api-key>c23e830d9b092a3a801d7f49b46</api-key> <links> <link> <rel>clients</rel> <uri>https://invoicefu.com/api/accounts/3-javier-ramirez/clients</uri> <methods>GET,POST</methods> </link> <link> <rel>new_client</rel> <uri>https://invoicefu.com/api/accounts/3-javier-ramirez/clients/new</uri> <methods>GET</methods> </link>
  27. 27. Rob Eisenberg<productions> <links> <link rel="self" href="..." /> <link rel="next" href="..." /> </links> <production> <name>RavenDB</name> <author>Oren Eini</author> <links> <link rel="self" href="..." /> <link rel="rels/episodes" href="..." /> </links> </production> <production> <name>Art of Speaking</name> <author>Scott Hanselman</author> <links> <link rel="self" href="..." /> <link rel="rels/episodes" href="..." /> </links> </production> <!--other productions elided--></productions>
  28. 28. Mike Kelly{ "_links": { "self": { "href": "..." } }, "title": "Real World ASP.NET MVC3", "description": "In this advanced, somewhat-opinionated...", "permitted": true, "_embedded": { "episodes": [{ "_links": { "self": { "href": "..." }, "media": [{ "type": "video/webm; codecs=vp8.0, vorbis", "href": "..." },{ "type": "video/ogg; codecs=theora, vorbis", "href": "..." }] }, "title": "Foundations", "description": "In this episode we talk about what it is were doing: building ourstartup and getting ourselves off the ground. We take..", "released": 1306972800 }
  29. 29. DARREL MILLER{ "_links" : { "self" : { "href" : "/user/95/allproductions" }, }, "name" : "Joe", "_embedded" : { "urn:tekpub:production" : [ { "_links": { "self": { "href": "/production/22" }, }, "allowed" : "true", "title" : "Rails runs rings round ReST resource representations" }, { "_links": { "self": { "href": "/production/74" }, }, "allowed" : "false", "title" : "Surfing the waves beats surfing an API" } ] }}
  30. 30. ACTS AS API :Filtros
  31. 31. URI templateshttp://example.com/~{username}/http://example.com/dictionary/{term:1}/{term}http://example.com/search{?q,lang}
  32. 32. > curl "https://invoicefu.com/api/accounts/108-cole-mertz-fake/invoices/new?api_key=ddd349b30b6d9fde97b01b827e6be5ed1e4fbe72&format=xml&debug=1"<?xml version="1.0" encoding="UTF-8"?><errors> <error>extra params found: debug. Allowed params are:account_id,client_id,invoice_id,proforma_id</error></errors>> curl "https://invoicefu.com/api/accounts/108-cole-mertz-fake/invoices/new?api_key=ddd349b30b6d9fde97b01b827e6be5ed1e4fbe72&format=xml&debug=1&strict=false"<?xml version="1.0" encoding="UTF-8"?><invoice> <number>2011/30</number> <issued-on>2011-12-11</issued-on> <proforma-id nil="true"></proforma-id> (...) <links> (...) <link> <rel>invoices</rel> <uri>https://invoicefu-localhost.com/api/accounts/108-cole-mertz-fake/invoices</uri> <methods>GET,POST</methods> </link> </links></invoice>
  33. 33. templates for new resources> curl "https://invoicefu.com/api/accounts/108-cole-mertz-fake/invoices/new?api_key=ddd349b30b6d9fde97b027e6be5ed1e4fbe72&format=json"{"invoice":{"number":"2011/30","issued_on":"2011-12-12","proforma_id":null,"notes":null,"footer":null,"locale":"en","currency_code":"USD","currency_symbol":"$","ac_name":"Cole-Mertz#FAKE","ac_company_number_name":"Companynumber","ac_company_number":"25465828K","ac_tax_number_name":"VATNumber","ac_tax_number":"ES25464828k","ac_address":"234 brecknockroad","ac_city":"london","ac_province":null,"ac_postal_code":"n18 5bq","ac_country_name":"UnitedKingdom","cl_email":null,"cl_name":null,"cl_company_number_name":null,"cl_company_number":null,"cl_tax_number_name":null,"cl_tax_number":null,"cl_address":null,"cl_city":null,"cl_province":null,"cl_postal_code":null,"cl_country_name":null,"invoice_lines":[],"discount_percent":null,"tax_lines":[{"name":"TVA","signed_percent":"19.6"}],"paid":"0.0","links":[{"rel":"payments","uri":"https://invoicefu.com/api/accounts/108-cole-mertz-fake/invoices//payments","methods":"POST"},{"rel":"account","uri":"https://invoicefu.com/api/accounts/108-cole-mertz-fake","methods":"GET,PUT"},{"rel":"client","uri":null,"methods":"GET,PUT,DELETE"},{"rel":"proforma","uri":null,"methods":"GET,PUT,DELETE"},{"rel":"pdf","uri":null,"methods":"GET"},{"rel":"invoices","uri":"https://invoicefu.com/api/accounts/108-cole-mertz-fake/invoices","methods":"GET,POST"}]}}j
  34. 34. Multiple consumers
  35. 35. All your FORMATare belong to us*even native formats
  36. 36. javascript revival
  37. 37. Cross originresource sharing
  38. 38. use the metadata lukePermitir cabeceras del tipo return-async return-representation return-minimalDevolver cabeceras útiles
  39. 39. Respuestas parcialeshttps://gdata.youtube.com/feeds/api/users/default/uploads?fields=entry(title,gd:comments,yt:statistics)fields=entry[link/@rel=http://gdata.youtube.com/schemas/2007%23mobile]
  40. 40. Implementación en invoicefu
  41. 41. apigee
  42. 42. http://usemyapi.com 12 mayo 2012
  43. 43. APIs REST usableS* edición codemotion.es{"links":[ {"rel":"author", "uri":"http://javier-ramirez.com"}, {"rel":"work", "uri":"http://aspgems.com"}, {"rel":"blog", "uri":"http://formatinternet.com"}, {"rel":"twittEr", "uri":"http//twitter.com/supercoco9"}]}*ningún gatico (ni ningún friki ansioso) ha sido dañado para hacer esta presentación

×