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

RESTful para todos

RESTful para todos

Cómo diseñar APIs RESTful sin morir en el intento.

Vivimos en un mundo orientado a servicios interconectados. Las protagonistas de esta evolución: las APIs RESTful. Si tu aplicación está enfocada a servicios y al mundo entero tenés que saber cómo encararlas. Mostraré las mejores prácticas para diseñar APIs restful, desde su concepción hasta su ejecución, testing y documentación. Modelado de Entidades y colecciones, errores, estándares y mucho más. Con esta información estarás en condiciones de diseñar la API RESTful de tu próxima Startup multimillonaria :)

Realizada en:

- NetConf.uy Octubre 2014 (http://netconf.uy/)
- PHPmvd Noviembre 2014 (http://phpmvd.uy)

Diego Sapriza

October 03, 2014
Tweet

More Decks by Diego Sapriza

Other Decks in Technology

Transcript

  1. RESTful 4 all
    Diego Sapriza
    [email protected]
    @AV4TAr

    View Slide

  2. Como diseñar una API RESTful
    sin morir en el intento.

    View Slide

  3. Hi!Diego Sapriza
    I’M
    @AV4TAr

    View Slide

  4. View Slide

  5. PHP.meetup.uy

    DevOps.meetup.uy
    .
    .uy

    View Slide

  6. “El mundo evoluciona
    constantemente”

    View Slide

  7. Restful api
    versionamiento
    recursos
    status codes
    autenticación
    mensajes
    paginación
    documentación
    hypermedia (HATEOAS)
    verbos
    tools

    View Slide

  8. Quiénes hacen
    mayoritariamente
    Web dev?

    View Slide

  9. REpresentational State transfer
    técnica de arquitectura
    no es un estándar

    View Slide

  10. Acuerdo
    https://www.flickr.com/photos/[email protected]/

    View Slide

  11. View Slide

  12. Roy Fielding
    escalabilidad
    :(

    View Slide

  13. restricciones escalabilidad
    Client-Server
    Stateless
    Cache
    Uniform Interfaces
    Layered System
    Code on demand (opcional)

    View Slide

  14. Richardson Maturity Model
    http://bit.ly/api-rmm

    View Slide

  15. 0: The Swamp of POX
    RPC  SOBRE  HTTP  

    View Slide

  16. JSON
    XML
    html
    images

    View Slide

  17. 0: The Swamp of POX
    GET    
    http://srv.com/addin/auto-­‐harvest/end-­‐job/:id/
    errors/:errors_messages  
    http://srv.com/addin/auto-­‐harvest/start-­‐job/:id

    View Slide

  18. Richardson Maturity Model
    http://bit.ly/api-rmm

    View Slide

  19. Uniform Interfaces
    • Identificación recursos.
    • Manipulación de recursos a través de su
    representación.
    • Mensajes auto-descriptivos.
    • Hypermedia como motor del estado de la
    aplicación (HATEOAS).

    View Slide

  20. 1: RECURSOS
    tienen una URI
    mapean entidad/es
    sustantivos

    View Slide

  21. uri
    scheme:hierarchical part[?query][#fragment]
    telnet://192.168.1.1
    urn:isbn:978-1-449-3150-9
    mailto:[email protected]
    https://api.twilio.com/2010-­‐04-­‐01

    View Slide

  22. identificación
    /recurso/:id  
    /recurso/:id/:acción  
    /?r=recurso&id=:id  
    /?r=recurso&id=:id&a=:acción

    View Slide

  23. colecciones
    /recursos  
    /recursos/:id  
    /recursos/:id?pagina=:n&limite=100

    View Slide

  24. Richardson Maturity Model

    View Slide

  25. Uniform Interfaces
    • Identificación recursos.
    • Manipulación de recursos a través de su
    representación.
    • Mensajes auto-descriptivos.
    • Hypermedia como motor del estado de la
    aplicación (HATEOAS).

    View Slide

  26. Representación

    View Slide

  27. HTTP verbs
    Get Post Put Delete
    Patch Options Head
    Trace Connect
    http://bit.ly/http-­‐request-­‐methods

    View Slide

  28. crud http
    CREATE POST
    READ GET
    UPDATE PUT
    DELETE DELETE

    View Slide

  29. método seguro idempotente cachable
    GET
    HEAD
    POST
    PUT
    DELETE
    http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2

    View Slide

  30. GET /personas Obtener  lista  de  personas
    POST /personas Agregar  una  persona
    DELETE /personas/:id Eliminar  una  persona
    GET /personas/:id Obtener  una  persona
    PUT /personas/:id Actualizar  una  persona
    GET /personas/:id/contactos Obtener  los  contactos  de  
    una  persona
    POST /personas/:id/contactos Agregar  un  contacto  a  una  
    persona
    POST /personas/subirImagen Subir  una  imagen

    View Slide

  31. y ahora…
    ¿qué hacemos con estos msjs?

    View Slide

  32. Richardson Maturity Model

    View Slide

  33. Documentar…

    View Slide

  34. Uniform Interfaces
    • Identificación recursos.
    • Manipulación de recursos a través de su
    representación.
    • Mensajes auto-descriptivos.
    • Hypermedia como motor del estado de la
    aplicación (HATEOAS).

    View Slide

  35. auto-descriptivos
    ¿Cómo procesar el mensaje?
    ¿qué parser utilizar?
    ¿Caching?

    View Slide

  36. ahora…
    ¿cómo son los mensajes?
    HAL Collection JSON Siren

    View Slide

  37. HTTP/1.1 200 OK
    Content-Type: application/json
    {
    "status":"ok",
    "message":"Data retrieved OK!",
    "data" : [
    {
    "id": 90,
    "modelId": 81,
    "path": "Somewhere over the rainbow.rvt"
    },
    {
    "id": 91,
    "modelId": 13,
    "path": "Blue birds fly.rvt”
    }]
    }
    GET  http://server/addin/auto-­‐harvest/get-­‐jobs/
    o_O

    View Slide

  38. HTTP/1.1 200 OK
    Content-Type: application/json
    {
    "status":"error",
    "message":"Page not found”,
    "data" : []
    }
    o_O

    View Slide

  39. status codes
    2xx - Success
    3xx - Redirection
    4xx - Client Error
    5xx - Server Error

    View Slide

  40. Error messages
    api-problem
    HTTP/1.1 401 Unauthorized
    Content-Type: application/problem+json
    {
    "type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html",
    "title": "Unauthorized",
    "status": 401,
    "detail": "Unauthorized",
    "authentication_uri": "/oauth"
    }

    View Slide

  41. Uniform Interfaces
    • Identificación recursos.
    • Manipulación de recursos a través de su
    representación.
    • Mensajes auto-descriptivos.
    • Hypermedia como motor del estado de la
    aplicación (HATEOAS).

    View Slide

  42. HATEOAS
    Clients make state
    transitions only through
    actions that are dynamically identified within
    hypermedia by the server.
    Except for simple fixed entry points to
    the application, a client does not assume that any
    particular action is available for any particular
    resources beyond those described in
    representations previously received from the server.

    View Slide

  43. clase.php
    public class Customer
    {
    public $Id;
    public $Name;
    }

    View Slide

  44. json
    {
    "id" : "1"
    "name" : "Diego"
    }

    View Slide

  45. HAL
    http://bit.ly/hal-spec
    {
    "id": "diego",
    "name": "Diego Sapriza”,
    "_links": {
    "self": {
    "href": "http://web.org/api/users/diego"
    },
    "website": {
    "href": "http://web.org/api/locations/diego"
    }
    }
    }

    View Slide

  46. HAL
    {
    .. *snip* ..
    "_embedded": {
    "website": {
    "_links": {
    "self": {
    "href": “http://web.org/api/locations/diego"
    }
    },
    "id": "diego",
    "url": "http://diego.uy"
    }
    }
    }

    View Slide

  47. HAL - colecciones
    {
    "_links": {
    "self" :{ "href": "http://web.org/api/user?page=3" },
    "first":{ "href": "http://web.org/api/user" },
    "prev" :{ "href": "http://web.org/api/user?page=2" },
    "next" :{ "href": "http://web.org/api/user?page=4" },
    "last" :{ "href": "http://web.org/api/user?page=133" }
    },
    "count": 3,
    "total": 498,
    ...
    }

    View Slide

  48. https://api.github.com

    View Slide

  49. {
    "current_user_url": "https://api.github.com/user",
    "authorizations_url": "https://api.github.com/authorizations",
    "emails_url": "https://api.github.com/user/emails",
    "emojis_url": "https://api.github.com/emojis",
    "events_url": "https://api.github.com/events",
    "feeds_url": "https://api.github.com/feeds",
    "following_url": "https://api.github.com/user/following{/target}",
    "gists_url": "https://api.github.com/gists{/gist_id}",
    "hub_url": "https://api.github.com/hub",
    "issues_url": "https://api.github.com/issues",
    "keys_url": "https://api.github.com/user/keys",
    "notifications_url": "https://api.github.com/notifications",
    ...
    }
    https://api.github.com

    View Slide

  50. {
    "current_user_url": "https://api.github.com/user",
    "authorizations_url": "https://api.github.com/authorizations",
    "emails_url": "https://api.github.com/user/emails",
    "emojis_url": "https://api.github.com/emojis",
    "events_url": "https://api.github.com/events",
    "feeds_url": "https://api.github.com/feeds",
    "following_url": "https://api.github.com/user/following{/target}",
    "gists_url": "https://api.github.com/gists{/gist_id}",
    "hub_url": "https://api.github.com/hub",
    "issues_url": "https://api.github.com/issues",
    "keys_url": "https://api.github.com/user/keys",
    "notifications_url": "https://api.github.com/notifications",
    "organization_url": "https://api.github.com/orgs/{org}",
    "public_gists_url": "https://api.github.com/gists/public",
    "rate_limit_url": "https://api.github.com/rate_limit",
    "repository_url": "https://api.github.com/repos/{owner}/{repo}",
    "starred_url": "https://api.github.com/user/starred{/owner}{/repo}",
    "starred_gists_url": "https://api.github.com/gists/starred",
    "team_url": "https://api.github.com/teams",
    "user_url": "https://api.github.com/users/{user}",
    "user_organizations_url": "https://api.github.com/user/orgs",
    ...
    }

    View Slide

  51. Richardson Maturity Model
    http://bit.ly/api-rmm

    View Slide

  52. Sigamos links

    View Slide

  53. Restful api
    versionamiento
    recursos
    status codes
    autenticación
    mensajes
    paginación
    documentación
    hypermedia (HATEOAS)
    verbos
    tools

    View Slide

  54. Versiona tu API

    View Slide

  55. HTTP  GET  
    https://web.com/api/v1/users/diego

    View Slide

  56. HTTP  GET  
    https://web.com/api/users/diego  
    api-­‐version:  2

    View Slide

  57. HTTP  GET  
    https://web.com/api/users/diego  
    Accept:  application/vnd.myapi.v2+json

    View Slide

  58. HTTP  GET  
    https://web.com/api/users/diego
    por defecto última versión
    Headers para versiones anteriores

    View Slide

  59. autenticación

    View Slide

  60. crea tu propio método

    View Slide

  61. HTTP Basic Auth
    HTTP Digest
    OAuth2

    View Slide

  62. tools
    Postman
    Runscope
    jsonmate.com

    View Slide

  63. Restful api
    versionamiento
    recursos
    status codes
    autenticación
    mensajes
    paginación
    documentación
    hypermedia (HATEOAS)
    verbos
    tools

    View Slide

  64. View Slide

  65. @AV4TAr
    http://AV4TAr.com
    https://speakerdeck.com/av4tar/restful-para-todos

    View Slide

  66. View Slide

  67. We are hiring
    case.recruiterbox.com

    View Slide

  68. • http://www.troyhunt.com/2014/02/your-api-versioning-is-
    wrong-which-is.html
    • http://martinfowler.com/articles/
    richardsonMaturityModel.html
    • http://www.vinaysahni.com/best-practices-for-a-pragmatic-
    restful-api
    • http://spf13.com/post/soap-vs-rest
    • https://leanpub.com/build-apis-you-wont-hate
    • https://speakerdeck.com/caseysoftware/on-the-edge-of-
    hypermedia-midwest-dot-io

    View Slide