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 full-size slide

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

    View full-size slide

  3. Hi!Diego Sapriza
    I’M
    @AV4TAr

    View full-size slide

  4. PHP.meetup.uy

    DevOps.meetup.uy
    .
    .uy

    View full-size slide

  5. “El mundo evoluciona
    constantemente”

    View full-size slide

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

    View full-size slide

  7. Quiénes hacen
    mayoritariamente
    Web dev?

    View full-size slide

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

    View full-size slide

  9. Acuerdo
    https://www.flickr.com/photos/124247024@N07/

    View full-size slide

  10. Roy Fielding
    escalabilidad
    :(

    View full-size slide

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

    View full-size slide

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

    View full-size slide

  13. 0: The Swamp of POX
    RPC  SOBRE  HTTP  

    View full-size slide

  14. JSON
    XML
    html
    images

    View full-size slide

  15. 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 full-size slide

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

    View full-size slide

  17. 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 full-size slide

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

    View full-size slide

  19. 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 full-size slide

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

    View full-size slide

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

    View full-size slide

  22. Richardson Maturity Model

    View full-size slide

  23. 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 full-size slide

  24. Representación

    View full-size slide

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

    View full-size slide

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

    View full-size slide

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

    View full-size slide

  28. 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 full-size slide

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

    View full-size slide

  30. Richardson Maturity Model

    View full-size slide

  31. Documentar…

    View full-size slide

  32. 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 full-size slide

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

    View full-size slide

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

    View full-size slide

  35. 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 full-size slide

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

    View full-size slide

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

    View full-size slide

  38. 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 full-size slide

  39. 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 full-size slide

  40. 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 full-size slide

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

    View full-size slide

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

    View full-size slide

  43. 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 full-size slide

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

    View full-size slide

  45. 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 full-size slide

  46. https://api.github.com

    View full-size slide

  47. {
    "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 full-size slide

  48. {
    "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 full-size slide

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

    View full-size slide

  50. Sigamos links

    View full-size slide

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

    View full-size slide

  52. Versiona tu API

    View full-size slide

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

    View full-size slide

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

    View full-size slide

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

    View full-size slide

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

    View full-size slide

  57. autenticación

    View full-size slide

  58. crea tu propio método

    View full-size slide

  59. HTTP Basic Auth
    HTTP Digest
    OAuth2

    View full-size slide

  60. tools
    Postman
    Runscope
    jsonmate.com

    View full-size slide

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

    View full-size slide

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

    View full-size slide

  63. We are hiring
    case.recruiterbox.com

    View full-size slide

  64. • 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 full-size slide