RESTful APIs con Tastypie

  • 1,172 views
Uploaded on

 

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
1,172
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
7
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 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
  • 7. REST - ¿Cómo?
  • 8. REST - ¿Cómo? ?
  • 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 dont 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
  • 14. Ejemplo
  • 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: HelloWorld!}>>> headers = {content-type: application/json}>>> requests.post(url, data=json.dumps(data),headers=headers)
  • 21. Tastypie - 201HTTP/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/
  • 22. 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
  • 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 ACCEPTEDDate: Fri, 14 Sep 2012 13:56:38 GMTServer: WSGIServer/0.1 Python/2.7.3Content-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 CONTENTDate: Fri, 14 Sep 2012 14:02:48 GMTServer: WSGIServer/0.1 Python/2.7.3Content-Length: 0Content-Type: text/html; charset=utf-8
  • 25. Tastypie - Filtrosclass 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 sonsimples● 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 5789http://www.ics.uci.edu/~fielding/pubs/dissertation/●top.htm● RESTful Web Services – Oreilly(ROA)● http://www.w3.org/Provider/Style/URI.htmlhttp://roy.gbiv.com/untangled/2008/rest-apis-●