Download - RESTful APIs con Tastypie
RESTful APIs con Tastypie
Quin?
Santiago Basulto
@santiagobasulto
Athlete.com
https://github.com/santiagobasulto
Temario
APIs
REST
HTTP
Ejemplo
API
Consumidas por mquinas
Fcil de usar y aprender (poca documentacin)
Difcil de mal usar
Apuntada a la audiencia adecuada
Quin 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
Encapsulacin
REST - Cmo?
REST - Cmo?
?
RESTful
HTTP
ROA
HATEOAS WTF?
HTTP
Mtodos (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
Aplicacin de Django.
Permite crear recursos basados en modelos
Extensible y customizable
Mltiples modos de serializacin
Buen uso de HTTP
HATEOAS por defecto
Tests y docs
RESTful
Ejemplo
Tastypie - Instalacin
$ pip install django-tastypie
# INSTALLED_APPS += ['tastypie']
$ manage.py syncdb
Tastypie - Setup
$ mkdir api$ touch api/__init__.py$ touch api/resources.py
Al cdigo!
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)
t: step4_POSTing
Tastypie - 201
HTTP/1.0 201 CREATEDDate: Fri, 14 Sep 2012 13:32:24 GMTServer: WSGIServer/0.1 Python/2.7Content-Type: text/html; charset=utf-8Location: 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 CONTENTDate: Fri, 14 Sep 2012 13:53:33 GMTServer: WSGIServer/0.1 Python/2.7.3Content-Length: 0Content-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 ACCEPTEDDate: Fri, 14 Sep 2012 13:56:38 GMTServer: WSGIServer/0.1 Python/2.7.3Content-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 CONTENTDate: Fri, 14 Sep 2012 14:02:48 GMTServer: WSGIServer/0.1 Python/2.7.3Content-Length: 0Content-Type: text/html; charset=utf-8
Tastypie - Filtros
/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
class Meta: filtering = { 'username': ALL, 'date_joined': ['range', 'gt', 'gte', 'lt', 'lte'], }(t: step6_basic_filtering)
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
Validacin de datos (t: step10_validation)
Tastypie - Autenticacin
Responde a la pregunta > Quin sos?
class Meta: authentication = TwitterAuthentication()class TwitterAuthentication(Authentication): def is_authenticated(self, request, **kwargs): return True
Tastypie - Autorizacin
Responde a la pregunta > Pods hacer eso?
class Meta: authorization = TwitterAuthorization()class TwitterAuthorization(Authorization): def is_authorized(self, request, object=None): return True
Cdigo 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-must-be-hypertext-driven