SlideShare una empresa de Scribd logo
RESTful APIs con
   Tastypie
¿Quién?
●
    Santiago Basulto
●
    @santiagobasulto
●
    Athlete.com
●
    https://github.com/santiagobasulto
Temario
●
    APIs
●
    REST
●
    HTTP
●
    Ejemplo
API
●
    Consumidas por máquinas
●
    Fácil de usar y aprender (poca documentación)
●
    Difícil de “mal usar”
●
    Apuntada a la audiencia adecuada
●
    ¿Quién es tu usuario?
REST - ¿Qué?
●
    REpresentational State Transfer
●
    “Estilo de Arquitectura”
●
    Cliente – Servidor
●
    Sin Estado (Stateless)
●
    Cacheable
●
    Interfaz Uniforme
●
    Capas
REST - ¿Por Qué?
●
    Escalable
●
    Generalidad
●
    Independiente
●
    Latencia
●
    Seguridad
●
    Encapsulación
REST - ¿Cómo?
REST - ¿Cómo?




    ?
RESTful
●
    HTTP
●
    ROA
●
    HATEOAS → WTF?
HTTP
●
    Métodos (GET, POST, PUT, DELETE, PATCH)
●
    Status codes (200, 201, 202, 301, 400, 401,

404)
●
    Headers (Content-Type, Accept, Authorization)
●
    Idempotencia
●
    NO USAR COOKIES!
ROA
●
    Resource Oriented Architecture
●
    Orientado a recursos, no a acciones (SOA)
●
    Recursos identificados por URIs
●
    Recursos → Representaciones
●
    “Cool URIs don't change”
HATEOAS
●
    Hypermedia As The Engine Of Application State
●
    “Todo es un recurso identificable”
●
    “Tu usuario no conoce nada”
●
    http://roy.gbiv.com/untangled/2008/rest-apis-

must-be-hypertext-driven
●
    http://en.wikipedia.org/wiki/HATEOAS
Tastypie
●
    Aplicación de Django.
●
    Permite crear recursos basados en modelos
●
    Extensible y customizable
●
    Múltiples modos de serialización
●
    Buen uso de HTTP
●
    HATEOAS por defecto
●
    Tests y docs
Ejemplo
Tastypie - Instalación
$ pip install django-tastypie

# INSTALLED_APPS += ['tastypie']

$ manage.py syncdb
Tastypie - Setup
$ mkdir api
$ touch api/__init__.py
$ touch api/resources.py
Al código!



         Tag: step1_setup
Tastypie - Pruebas
- /api/v1/
- /api/v1/user/
- /api/v1/user/schema/
- /api/v1/user/1/
- /api/v1/user/1/?format=xml
Tastypie - Customizando
- password? is_staff? @55f6589
- Crear otro recurso (t: step2_otro_recurso)
- Fields, recursos relacionados
              (t: step3_recursos_relacionados)
Tastypie - POSTing
>>> import json
>>> import requests

>>> url = "http://127.0.0.1:8000/api/v1/tweet/"

>>> data = {'user': '/api/v1/user/1/', 'tweet': 'Hello
World!'}

>>> headers = {'content-type': 'application/json'}

>>> requests.post(url, data=json.dumps(data),
headers=headers)
Tastypie - 201
HTTP/1.0 201 CREATED
Date: Fri, 14 Sep 2012 13:32:24 GMT
Server: WSGIServer/0.1 Python/2.7
Content-Type: text/html; charset=utf-8
Location: http://127.0.0.1:8000/api/v1/tweet/2/
Tastypie - DELETE
$ curl --dump-header - -XDELETE 
> http://localhost:8000/api/v1/tweet/2/

HTTP/1.0 204 NO CONTENT
Date: Fri, 14 Sep 2012 13:53:33 GMT
Server: WSGIServer/0.1 Python/2.7.3
Content-Length: 0
Content-Type: text/html; charset=utf-8
Tastypie – PATCH
$ curl --dump-header - -H "Content-Type:
application/json" 
> -X PATCH --data '{"tweet": "PATCHed tweet"}' 
> http://127.0.0.1:8000/api/v1/tweet/3/

HTTP/1.0 202 ACCEPTED
Date: Fri, 14 Sep 2012 13:56:38 GMT
Server: WSGIServer/0.1 Python/2.7.3
Content-Type: text/html; charset=utf-8
Tastypie – PUT
$ curl --dump-header - -H "Content-Type:
application/json" 
> -X PUT --data 
> '{"tweet": "PUT tweet", "user": "/api/v1/user/2/"}'
> http://127.0.0.1:8000/api/v1/tweet/3/

HTTP/1.0 204 NO CONTENT
Date: Fri, 14 Sep 2012 14:02:48 GMT
Server: WSGIServer/0.1 Python/2.7.3
Content-Length: 0
Content-Type: text/html; charset=utf-8
Tastypie - Filtros
class Meta:
   filtering = {
       'username': ALL,
       'date_joined': ['range', 'gt', 'gte', 'lt', 'lte'],
   }
                                       (t:
step6_basic_filtering)
●
    /api/v1/user/?username__startswith=a
●
    /api/v1/user/?username__exact=admin
●
    /api/v1/user/?username__iexact=Admin
●
 /api/v1/user/?date_joined__gte=2012-09-14
Tastypie - Datos complejos
●
    A veces los datos de los recursos no son

simples
●
    Dehydrate per-field (t: step6_basic_filtering)
●
    Dehydrate general(t: step8_general_dehydrate)
●
    Hydrate general (t: step9_general_hydrate)
●
    Hydrate Fields
●
    Validación de datos (t: step10_validation)
Tastypie - Autenticación
●
    Responde a la pregunta

       > ¿Quién sos?

class Meta:
   authentication = TwitterAuthentication()

class TwitterAuthentication(Authentication):

    def is_authenticated(self, request, **kwargs):
       return True
Tastypie - Autorización
●
    Responde a la pregunta

       > ¿Podés hacer eso?

class Meta:
   authorization = TwitterAuthorization()

class TwitterAuthorization(Authorization):

    def is_authorized(self, request, object=None):
       return True
Código usado
●
    https://github.com/santiagobasulto/tastypie-pyday-cba



(Está dividido por tags)
Recursos
●
    RFC 1626
●
    RFC 5789

http://www.ics.uci.edu/~fielding/pubs/dissertation/
●




top.htm
●
    RESTful Web Services – O'reilly(ROA)
●
    http://www.w3.org/Provider/Style/URI.html

http://roy.gbiv.com/untangled/2008/rest-apis-
●

Más contenido relacionado

PPTX
Introduction to HTTP - Hypertext Transfer Protocol
PDF
21 Hidden LinkedIn Hacks Revealed
PDF
PDF
Postman.pdf
ODP
Servicios web con Python
PDF
WORKSHOP I: Introducción a API REST
PPTX
Taller definición de apis
PDF
RESTful Para todos by Diego Sapriza
Introduction to HTTP - Hypertext Transfer Protocol
21 Hidden LinkedIn Hacks Revealed
Postman.pdf
Servicios web con Python
WORKSHOP I: Introducción a API REST
Taller definición de apis
RESTful Para todos by Diego Sapriza

Similar a RESTful APIs con Tastypie (20)

PPTX
Define y desarrolla tu primera api
PDF
APIs REST: Django y Go
ODP
Web framework ligeros y micros en java barcamp 2014
PDF
Web services restful con JAX-RS
PDF
ODP
Desarrollando un API con REST
PPTX
Servicios REST con Jersey
PDF
(20.05.2009) Cumuy Presenta - Más tecnologías interesantes para conocer - PPT 1
PDF
REST - deSymfony2012
PDF
Semana 7 Servicios Web REST con MongoDB final
PPTX
Fundamentos para el diseño de una RESTful API pragmática
PDF
Semana 7 Servicios Web API REST con Mongodb
PDF
Rest Conf Rails
PDF
Presentacion web2py
PDF
Api rest client en Android
PPTX
Seminario IV: REST & Jersey
PDF
APIs REST #devfestBilbao
PDF
Cómo crear un RESTful API con Go
PDF
Mi Primera Aplicacion en Google App Engine
PDF
5.2. api-rest
Define y desarrolla tu primera api
APIs REST: Django y Go
Web framework ligeros y micros en java barcamp 2014
Web services restful con JAX-RS
Desarrollando un API con REST
Servicios REST con Jersey
(20.05.2009) Cumuy Presenta - Más tecnologías interesantes para conocer - PPT 1
REST - deSymfony2012
Semana 7 Servicios Web REST con MongoDB final
Fundamentos para el diseño de una RESTful API pragmática
Semana 7 Servicios Web API REST con Mongodb
Rest Conf Rails
Presentacion web2py
Api rest client en Android
Seminario IV: REST & Jersey
APIs REST #devfestBilbao
Cómo crear un RESTful API con Go
Mi Primera Aplicacion en Google App Engine
5.2. api-rest
Publicidad

Último (20)

PPT
Que son las redes de computadores y sus partes
PDF
5.1 Pinch y Bijker en libro Actos, actores y artefactos de Bunch Thomas (coor...
PDF
Estrategia de apoyo tecnología miguel angel solis
PPTX
RAP02 - TECNICO SISTEMAS TELEINFORMATICOS.pptx
PPTX
RAP01 - TECNICO SISTEMAS TELEINFORMATICOS.pptx
PPTX
Presentación PASANTIAS AuditorioOO..pptx
PDF
Estrategia de apoyo tecnología grado 9-3
PDF
Calidad desde el Docente y la mejora continua .pdf
PPTX
IA de Cine - Como MuleSoft y los Agentes estan redefiniendo la realidad
PPTX
REDES INFORMATICAS REDES INFORMATICAS.pptx
PPTX
sa-cs-82-powerpoint-hardware-y-software_ver_4.pptx
PPTX
Presentación de Redes de Datos modelo osi
PPTX
Acronis Cyber Protect Cloud para Ciber Proteccion y Ciber Seguridad LATAM - A...
PDF
Instrucciones simples, respuestas poderosas. La fórmula del prompt perfecto.
PDF
MANUAL TECNOLOGÍA SER MINISTERIO EDUCACIÓN
PDF
Maste clas de estructura metálica y arquitectura
PDF
Influencia-del-uso-de-redes-sociales.pdf
PDF
Plantilla para Diseño de Narrativas Transmedia.pdf
PPTX
Power Point Nicolás Carrasco (disertación Roblox).pptx
PDF
Diapositiva proyecto de vida, materia catedra
Que son las redes de computadores y sus partes
5.1 Pinch y Bijker en libro Actos, actores y artefactos de Bunch Thomas (coor...
Estrategia de apoyo tecnología miguel angel solis
RAP02 - TECNICO SISTEMAS TELEINFORMATICOS.pptx
RAP01 - TECNICO SISTEMAS TELEINFORMATICOS.pptx
Presentación PASANTIAS AuditorioOO..pptx
Estrategia de apoyo tecnología grado 9-3
Calidad desde el Docente y la mejora continua .pdf
IA de Cine - Como MuleSoft y los Agentes estan redefiniendo la realidad
REDES INFORMATICAS REDES INFORMATICAS.pptx
sa-cs-82-powerpoint-hardware-y-software_ver_4.pptx
Presentación de Redes de Datos modelo osi
Acronis Cyber Protect Cloud para Ciber Proteccion y Ciber Seguridad LATAM - A...
Instrucciones simples, respuestas poderosas. La fórmula del prompt perfecto.
MANUAL TECNOLOGÍA SER MINISTERIO EDUCACIÓN
Maste clas de estructura metálica y arquitectura
Influencia-del-uso-de-redes-sociales.pdf
Plantilla para Diseño de Narrativas Transmedia.pdf
Power Point Nicolás Carrasco (disertación Roblox).pptx
Diapositiva proyecto de vida, materia catedra
Publicidad

RESTful APIs con Tastypie

  • 1. RESTful APIs con Tastypie
  • 2. ¿Quién? ● Santiago Basulto ● @santiagobasulto ● Athlete.com ● https://github.com/santiagobasulto
  • 3. Temario ● APIs ● REST ● HTTP ● Ejemplo
  • 4. API ● Consumidas por máquinas ● Fácil de usar y aprender (poca documentación) ● Difícil de “mal usar” ● Apuntada a la audiencia adecuada ● ¿Quién es tu usuario?
  • 5. REST - ¿Qué? ● REpresentational State Transfer ● “Estilo de Arquitectura” ● Cliente – Servidor ● Sin Estado (Stateless) ● Cacheable ● Interfaz Uniforme ● Capas
  • 6. REST - ¿Por Qué? ● Escalable ● Generalidad ● Independiente ● Latencia ● Seguridad ● Encapsulación
  • 9. RESTful ● HTTP ● ROA ● HATEOAS → WTF?
  • 10. HTTP ● Métodos (GET, POST, PUT, DELETE, PATCH) ● Status codes (200, 201, 202, 301, 400, 401, 404) ● Headers (Content-Type, Accept, Authorization) ● Idempotencia ● NO USAR COOKIES!
  • 11. ROA ● Resource Oriented Architecture ● Orientado a recursos, no a acciones (SOA) ● Recursos identificados por URIs ● Recursos → Representaciones ● “Cool URIs don't change”
  • 12. HATEOAS ● Hypermedia As The Engine Of Application State ● “Todo es un recurso identificable” ● “Tu usuario no conoce nada” ● http://roy.gbiv.com/untangled/2008/rest-apis- must-be-hypertext-driven ● http://en.wikipedia.org/wiki/HATEOAS
  • 13. Tastypie ● Aplicación de Django. ● Permite crear recursos basados en modelos ● Extensible y customizable ● Múltiples modos de serialización ● Buen uso de HTTP ● HATEOAS por defecto ● Tests y docs
  • 15. Tastypie - Instalación $ pip install django-tastypie # INSTALLED_APPS += ['tastypie'] $ manage.py syncdb
  • 16. Tastypie - Setup $ mkdir api $ touch api/__init__.py $ touch api/resources.py
  • 17. Al código! Tag: step1_setup
  • 18. Tastypie - Pruebas - /api/v1/ - /api/v1/user/ - /api/v1/user/schema/ - /api/v1/user/1/ - /api/v1/user/1/?format=xml
  • 19. Tastypie - Customizando - password? is_staff? @55f6589 - Crear otro recurso (t: step2_otro_recurso) - Fields, recursos relacionados (t: step3_recursos_relacionados)
  • 20. Tastypie - POSTing >>> import json >>> import requests >>> url = "http://127.0.0.1:8000/api/v1/tweet/" >>> data = {'user': '/api/v1/user/1/', 'tweet': 'Hello World!'} >>> headers = {'content-type': 'application/json'} >>> requests.post(url, data=json.dumps(data), headers=headers)
  • 21. Tastypie - 201 HTTP/1.0 201 CREATED Date: Fri, 14 Sep 2012 13:32:24 GMT Server: WSGIServer/0.1 Python/2.7 Content-Type: text/html; charset=utf-8 Location: http://127.0.0.1:8000/api/v1/tweet/2/
  • 22. Tastypie - DELETE $ curl --dump-header - -XDELETE > http://localhost:8000/api/v1/tweet/2/ HTTP/1.0 204 NO CONTENT Date: Fri, 14 Sep 2012 13:53:33 GMT Server: WSGIServer/0.1 Python/2.7.3 Content-Length: 0 Content-Type: text/html; charset=utf-8
  • 23. Tastypie – PATCH $ curl --dump-header - -H "Content-Type: application/json" > -X PATCH --data '{"tweet": "PATCHed tweet"}' > http://127.0.0.1:8000/api/v1/tweet/3/ HTTP/1.0 202 ACCEPTED Date: Fri, 14 Sep 2012 13:56:38 GMT Server: WSGIServer/0.1 Python/2.7.3 Content-Type: text/html; charset=utf-8
  • 24. Tastypie – PUT $ curl --dump-header - -H "Content-Type: application/json" > -X PUT --data > '{"tweet": "PUT tweet", "user": "/api/v1/user/2/"}' > http://127.0.0.1:8000/api/v1/tweet/3/ HTTP/1.0 204 NO CONTENT Date: Fri, 14 Sep 2012 14:02:48 GMT Server: WSGIServer/0.1 Python/2.7.3 Content-Length: 0 Content-Type: text/html; charset=utf-8
  • 25. Tastypie - Filtros class Meta: filtering = { 'username': ALL, 'date_joined': ['range', 'gt', 'gte', 'lt', 'lte'], } (t: step6_basic_filtering) ● /api/v1/user/?username__startswith=a ● /api/v1/user/?username__exact=admin ● /api/v1/user/?username__iexact=Admin ● /api/v1/user/?date_joined__gte=2012-09-14
  • 26. Tastypie - Datos complejos ● A veces los datos de los recursos no son simples ● Dehydrate per-field (t: step6_basic_filtering) ● Dehydrate general(t: step8_general_dehydrate) ● Hydrate general (t: step9_general_hydrate) ● Hydrate Fields ● Validación de datos (t: step10_validation)
  • 27. Tastypie - Autenticación ● Responde a la pregunta > ¿Quién sos? class Meta: authentication = TwitterAuthentication() class TwitterAuthentication(Authentication): def is_authenticated(self, request, **kwargs): return True
  • 28. Tastypie - Autorización ● Responde a la pregunta > ¿Podés hacer eso? class Meta: authorization = TwitterAuthorization() class TwitterAuthorization(Authorization): def is_authorized(self, request, object=None): return True
  • 29. Código usado ● https://github.com/santiagobasulto/tastypie-pyday-cba (Está dividido por tags)
  • 30. Recursos ● RFC 1626 ● RFC 5789 http://www.ics.uci.edu/~fielding/pubs/dissertation/ ● top.htm ● RESTful Web Services – O'reilly(ROA) ● http://www.w3.org/Provider/Style/URI.html http://roy.gbiv.com/untangled/2008/rest-apis- ●