SlideShare a Scribd company logo
UnRESTful APIs
with Django
Ari Lacenski
@tensory
June 25, 2013
Tuesday, June 25, 13
Why create an API?
API stands for Application Programming Interface.
An API to your project lets people write applications
that use your technology.
Web APIs are collections of URLs pointing to services.
Tuesday, June 25, 13
Remote Procedure Call
Uses URL patterns to suggest what you get back
like: yoursite.com/show/articles?article_id=42
Used to be super common, until REST pattern emerged
good luck with that
Often inconsistent &
needs a lot of docs
Response data isn’t
linked to DB records
Tuesday, June 25, 13
REST
(REpresentational State Transfer)
Uses HTTP concepts: GET, POST, DELETE & PUT
Super useful, super popular!
Lets you build an API that directly represents the data
that you want developers to work with
Tuesday, June 25, 13
REST
GET /article/42 returns JSON representation of article
with id=42
POST /article/ gets back JSON with a saved article ID
GET /article/ gets back a list of article IDs
{ ‘article’: { ‘id’: 42, ‘author’: ‘Becky
Smith’, ‘title’: ‘API Design 101’ }}
Tuesday, June 25, 13
REST works great.
“RESTful API” designs try to follow the REST pattern.
There are free API libraries for Python web frameworks.
This all works well for creating APIs to relational data.
BUT WAIT
What if your data is too complex to store in a DB table?
Tuesday, June 25, 13
Extend your pattern.
Consider a photo service with some color search tools.
Upload a photo? POST to /upload/ with file + metadata
Get photo details? GET /photo/
Want to let your API users calculate the average color in
some random images? ... Hmm.
Tuesday, June 25, 13
Let’s make it happen.
Tuesday, June 25, 13
models.py
from django.db import models
class Photo(models.Model):
uploader = models.ForeignKey(User)
uploaded_at = models.DateTimeField()
file = models.FileField(blank=True, null=True)
How do you turn this model into an API?
Try Tastypie.
Tuesday, June 25, 13
from tastypie.resources import Resource
from models import Photo
class PhotoResource(Resource):
class Meta(object):
queryset = Photo.objects.all()
resource_name = ‘photo’
allowed_methods = [‘get’, ‘post’, ‘put’]
api.py
Tuesday, June 25, 13
urls.py
from tastypie.api import Api
from api import PhotoResource
photo_api = Api(api_name='api')
urlpatterns = patterns(‘’, include(photo_api.urls))
# ... other routes in your app can go
# into this urlpatterns definition, if you want
Tuesday, June 25, 13
Can we upload photos?
Can we get back one photo’s data?
Can we see data about all photos
we’ve uploaded?
Yup.
Sure.
Check it out.
GET /api/photo/42
GET /api/photo/
POST /api/photo/
Where are we now?
Tuesday, June 25, 13
But what about that
color method?
id=34
id=60
id=29
Tuesday, June 25, 13
1. In api.py, add a method to your API’s
PhotoResource.
2. In views.py, create any helper methods you need
for your Photo model.
3. In api.py, use prepend_urls to add an RPC URL
pattern for the new PhotoResource method.
Mix in an RPC URL.
Tuesday, June 25, 13
import views
from tastypie.resources import Resource
from models import Photo
class PhotoResource(Resource):
class Meta(object):
queryset = Photo.objects.all()
resource_name = ‘photo’
allowed_methods = [‘get’, ‘post’, ‘put’]
def prepend_urls(self):
return [
url(r”^(?P<resource_name>)/average/” %
self._meta.resource_name, self.wrap_view('get_average_color'))
]
def get_average_color(self, request):
photo_ids = request.getlist(‘ids’)
# Add a get_average_color method to your app views.
result = views.get_average_color(photo_ids)
return { ‘color’: result.color_code }
api.py
Tuesday, June 25, 13
You’re done!
GET /api/photo/average?ids=34,60,29
{ ‘color’: ‘BAB5B2’ }
Tuesday, June 25, 13
Find out more
Comparison of REST vs XML RPC
http://bit.ly/8lkoPK
Django API packages comparison
https://www.djangopackages.com/grids/g/api/
Tastypie
http://django-tastypie.readthedocs.org/
https://github.com/toastdriven/django-tastypie
Tuesday, June 25, 13
Thanks for listening!
Ari Lacenski @tensory
Tuesday, June 25, 13

More Related Content

Similar to UnRESTful APIs with Django

Timeline SoMa WADE
Timeline SoMa WADETimeline SoMa WADE
Timeline SoMa WADE
Irnuk
 
Crafting [Better] API Clients
Crafting [Better] API ClientsCrafting [Better] API Clients
Crafting [Better] API Clients
Wellfire Interactive
 
Backbone
BackboneBackbone
Backbone
Ynon Perek
 
Art & music vs Google App Engine
Art & music vs Google App EngineArt & music vs Google App Engine
Art & music vs Google App Engine
thomas alisi
 
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
Amazon Web Services
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Joaquim Rocha
 
Grails Advanced
Grails Advanced Grails Advanced
Grails Advanced
Saurabh Dixit
 
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 MinutesDjangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Nina Zakharenko
 
React HOCs, Context and Observables
React HOCs, Context and ObservablesReact HOCs, Context and Observables
React HOCs, Context and Observables
Trayan Iliev
 
How to build an AngularJS backend-ready app WITHOUT BACKEND
How to build an AngularJS backend-ready app WITHOUT BACKEND How to build an AngularJS backend-ready app WITHOUT BACKEND
How to build an AngularJS backend-ready app WITHOUT BACKEND
Enrique Oriol Bermúdez
 
Reactive Java Microservices with Spring Boot and JHipster - Spring I/O 2022
Reactive Java Microservices with Spring Boot and JHipster - Spring I/O 2022Reactive Java Microservices with Spring Boot and JHipster - Spring I/O 2022
Reactive Java Microservices with Spring Boot and JHipster - Spring I/O 2022
Matt Raible
 
Building a Bibliography
Building a BibliographyBuilding a Bibliography
Building a Bibliography
Eric Aitala
 
Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.
Eugene Lazutkin
 
PHP Unit Testing in Yii
PHP Unit Testing in YiiPHP Unit Testing in Yii
PHP Unit Testing in Yii
IlPeach
 
An introduction to Ember.js
An introduction to Ember.jsAn introduction to Ember.js
An introduction to Ember.js
codeofficer
 
Introduction to Google App Engine
Introduction to Google App EngineIntroduction to Google App Engine
Introduction to Google App Engine
Andrea Spadaccini
 
d.mix: Programming by a Sample
d.mix: Programming by a Sampled.mix: Programming by a Sample
d.mix: Programming by a Sample
Leslie W
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
Daniel Spector
 
Advanced Web Development
Advanced Web DevelopmentAdvanced Web Development
Advanced Web Development
Robert J. Stein
 
Get up and running with google app engine in 60 minutes or less
Get up and running with google app engine in 60 minutes or lessGet up and running with google app engine in 60 minutes or less
Get up and running with google app engine in 60 minutes or less
zrok
 

Similar to UnRESTful APIs with Django (20)

Timeline SoMa WADE
Timeline SoMa WADETimeline SoMa WADE
Timeline SoMa WADE
 
Crafting [Better] API Clients
Crafting [Better] API ClientsCrafting [Better] API Clients
Crafting [Better] API Clients
 
Backbone
BackboneBackbone
Backbone
 
Art & music vs Google App Engine
Art & music vs Google App EngineArt & music vs Google App Engine
Art & music vs Google App Engine
 
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Grails Advanced
Grails Advanced Grails Advanced
Grails Advanced
 
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 MinutesDjangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
 
React HOCs, Context and Observables
React HOCs, Context and ObservablesReact HOCs, Context and Observables
React HOCs, Context and Observables
 
How to build an AngularJS backend-ready app WITHOUT BACKEND
How to build an AngularJS backend-ready app WITHOUT BACKEND How to build an AngularJS backend-ready app WITHOUT BACKEND
How to build an AngularJS backend-ready app WITHOUT BACKEND
 
Reactive Java Microservices with Spring Boot and JHipster - Spring I/O 2022
Reactive Java Microservices with Spring Boot and JHipster - Spring I/O 2022Reactive Java Microservices with Spring Boot and JHipster - Spring I/O 2022
Reactive Java Microservices with Spring Boot and JHipster - Spring I/O 2022
 
Building a Bibliography
Building a BibliographyBuilding a Bibliography
Building a Bibliography
 
Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.Practical pairing of generative programming with functional programming.
Practical pairing of generative programming with functional programming.
 
PHP Unit Testing in Yii
PHP Unit Testing in YiiPHP Unit Testing in Yii
PHP Unit Testing in Yii
 
An introduction to Ember.js
An introduction to Ember.jsAn introduction to Ember.js
An introduction to Ember.js
 
Introduction to Google App Engine
Introduction to Google App EngineIntroduction to Google App Engine
Introduction to Google App Engine
 
d.mix: Programming by a Sample
d.mix: Programming by a Sampled.mix: Programming by a Sample
d.mix: Programming by a Sample
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
Advanced Web Development
Advanced Web DevelopmentAdvanced Web Development
Advanced Web Development
 
Get up and running with google app engine in 60 minutes or less
Get up and running with google app engine in 60 minutes or lessGet up and running with google app engine in 60 minutes or less
Get up and running with google app engine in 60 minutes or less
 

Recently uploaded

みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
TIPNGVN2
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Zilliz
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 

Recently uploaded (20)

みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 

UnRESTful APIs with Django

  • 1. UnRESTful APIs with Django Ari Lacenski @tensory June 25, 2013 Tuesday, June 25, 13
  • 2. Why create an API? API stands for Application Programming Interface. An API to your project lets people write applications that use your technology. Web APIs are collections of URLs pointing to services. Tuesday, June 25, 13
  • 3. Remote Procedure Call Uses URL patterns to suggest what you get back like: yoursite.com/show/articles?article_id=42 Used to be super common, until REST pattern emerged good luck with that Often inconsistent & needs a lot of docs Response data isn’t linked to DB records Tuesday, June 25, 13
  • 4. REST (REpresentational State Transfer) Uses HTTP concepts: GET, POST, DELETE & PUT Super useful, super popular! Lets you build an API that directly represents the data that you want developers to work with Tuesday, June 25, 13
  • 5. REST GET /article/42 returns JSON representation of article with id=42 POST /article/ gets back JSON with a saved article ID GET /article/ gets back a list of article IDs { ‘article’: { ‘id’: 42, ‘author’: ‘Becky Smith’, ‘title’: ‘API Design 101’ }} Tuesday, June 25, 13
  • 6. REST works great. “RESTful API” designs try to follow the REST pattern. There are free API libraries for Python web frameworks. This all works well for creating APIs to relational data. BUT WAIT What if your data is too complex to store in a DB table? Tuesday, June 25, 13
  • 7. Extend your pattern. Consider a photo service with some color search tools. Upload a photo? POST to /upload/ with file + metadata Get photo details? GET /photo/ Want to let your API users calculate the average color in some random images? ... Hmm. Tuesday, June 25, 13
  • 8. Let’s make it happen. Tuesday, June 25, 13
  • 9. models.py from django.db import models class Photo(models.Model): uploader = models.ForeignKey(User) uploaded_at = models.DateTimeField() file = models.FileField(blank=True, null=True) How do you turn this model into an API? Try Tastypie. Tuesday, June 25, 13
  • 10. from tastypie.resources import Resource from models import Photo class PhotoResource(Resource): class Meta(object): queryset = Photo.objects.all() resource_name = ‘photo’ allowed_methods = [‘get’, ‘post’, ‘put’] api.py Tuesday, June 25, 13
  • 11. urls.py from tastypie.api import Api from api import PhotoResource photo_api = Api(api_name='api') urlpatterns = patterns(‘’, include(photo_api.urls)) # ... other routes in your app can go # into this urlpatterns definition, if you want Tuesday, June 25, 13
  • 12. Can we upload photos? Can we get back one photo’s data? Can we see data about all photos we’ve uploaded? Yup. Sure. Check it out. GET /api/photo/42 GET /api/photo/ POST /api/photo/ Where are we now? Tuesday, June 25, 13
  • 13. But what about that color method? id=34 id=60 id=29 Tuesday, June 25, 13
  • 14. 1. In api.py, add a method to your API’s PhotoResource. 2. In views.py, create any helper methods you need for your Photo model. 3. In api.py, use prepend_urls to add an RPC URL pattern for the new PhotoResource method. Mix in an RPC URL. Tuesday, June 25, 13
  • 15. import views from tastypie.resources import Resource from models import Photo class PhotoResource(Resource): class Meta(object): queryset = Photo.objects.all() resource_name = ‘photo’ allowed_methods = [‘get’, ‘post’, ‘put’] def prepend_urls(self): return [ url(r”^(?P<resource_name>)/average/” % self._meta.resource_name, self.wrap_view('get_average_color')) ] def get_average_color(self, request): photo_ids = request.getlist(‘ids’) # Add a get_average_color method to your app views. result = views.get_average_color(photo_ids) return { ‘color’: result.color_code } api.py Tuesday, June 25, 13
  • 16. You’re done! GET /api/photo/average?ids=34,60,29 { ‘color’: ‘BAB5B2’ } Tuesday, June 25, 13
  • 17. Find out more Comparison of REST vs XML RPC http://bit.ly/8lkoPK Django API packages comparison https://www.djangopackages.com/grids/g/api/ Tastypie http://django-tastypie.readthedocs.org/ https://github.com/toastdriven/django-tastypie Tuesday, June 25, 13
  • 18. Thanks for listening! Ari Lacenski @tensory Tuesday, June 25, 13