SlideShare a Scribd company logo
API Design & Security in
        Django
                Tareque Hossain
                Education  Technology



                                         1
2
Fundamentals of API
•  Architecture
•  Defining resources
•  Uniform response
•  Serialization
•  Versioning
•  Authentication

                          3
Your API should be RESTful

•  Stateless
•  Client-server
•  Cacheable
•  Uniform Interface
  o HTTP GET/POST/PUT/DELETE


                               4
Defining Resources
•  Resource
    o Cohesive set of information
    o Of interest to client


•  Identified by URL
    o Uniform Resource Locator
http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&photo_id=5983860647



                                                                                         5
Defining Resources..
•  Resource != Django Model
 o May consist of data from several different
   model instances
    • Attributes
    • Values returned from member functions
 o May contain data completely unrelated to
   any model instance
    • Date & time of response

                                                6
Resource: Example




                    7
Defining Resources...
•  Notice how:
  o Each instance of book has (similar to
    select_related):
     • Authors
     • Editions
     • Awards
  o is_favorite indicates whether the client
    user has marked this book as favorite

                                               8
Uniform Response




                   9
Uniform Response
•  Resource attributes vary wildly
•  Provide uniform response:
  o Include resource independent attributes
     • HTTP Status code
     • Error code (you define for your API)
     • Error message or data



                                              10
Uniformity: Example




http://api.pbslearningmedia.org/v1.0/likes/content/lsps07.sci.phys.matter


                                                                            11
Uniform Response
•  Include meta information:
  o Facets for certain attributes
     • Choices for form fields
  o Pagination (if applicable)
    • Result count
    • Page number
    • Resource per page


                                    12
Uniform Response
•  Present in all responses (GET/POST/
   PUT)
•  Not in response for DELETE
•  HTTP 1.1 forbids message body for
   1.xx, 204 (DELETE) & 304
•  Can be parsed by client even if it can’t
   parse the actual resource data

                                              13
Serialization
•  JSON rocks
•  RESTful API isn’t about restrictions
•  API should support:
  o JSONP
  o JSON
  o YAML
  o XML


                                          14
Serialization..
•  Have a default, say: JSON
   http://api.pbslearningmedia.org/v1.0/content/contents/cdda1ed2-da03




•  But if client requests different format,
   then deliver accordingly (if supported)

  http://api.pbslearningmedia.org/v1.0/content/contents/cdda1ed2-da03.xml




                                                                            15
Serialization..
•  Have a default, say: JSON
   http://api.pbslearningmedia.org/v1.0/content/contents/cdda1ed2-da03




•  But if client requests different format,
   then deliver accordingly (if supported)

  http://api.pbslearningmedia.org/v1.0/content/contents/cdda1ed2-da03.xml




                                                                            16
Versioning
•  APIs change all the time
  o Don’t break your existing API
  o Roll out new API set while old ones are
    functioning (if data models don’t change)
•  Save namespace
  o Old
          http://api.pbslearningmedia.org/v1.0/content/contents/cdda1ed2-da03


  o New
          http://api.pbslearningmedia.org/v2.0/content/contents/cdda1ed2-da03
                                                                                17
Versioning
•  Write separate URL definitions & handlers
   for different versions




                                               18
Authentication




                 19
Authentication
•  Not all APIs endpoints are public
•  Use authentication to protect your API
  o Oauth is great




        http://wiki.oauth.net/w/page/12238551/ServiceProviders
                                                                 20
Oauth: Overview
•  Two types of access:
  o Resource accessed by web applications
    directly
     •  User independent
     •  Accessing Twitter’s aggregated public
        timeline
  o Resource accessed by web applications on
    behalf of users
    • Accessing user’s private timeline
                                                21
Oauth: Overview
•  Credentials consist of:
  o Consumer key & secret (application)
  o Access token & token secret (user)
•  Each request contains:
  o  oauth_consumer_key
  o  oauth_token
  o  oauth_signature_method
  o  oauth_signature
  o  oauth_timestamp
  o  oauth_nonce
  o  oauth_version

                                          22
Oauth: 2-legged
•  Resource accessed by web
   applications directly
   o Use 2-legged Oauth
   o Leave oauth_token empty




 http://oauth.googlecode.com/svn/spec/ext/consumer_request/1.0/drafts/2/spec.html



                                                                                    23
Oauth: 3-legged
•  Resource accessed by web
   applications on behalf of users
  o Use 3-legged Oauth
  o User explicitly authorizes 3rd party
    applications to access protected resources
     • Allow apps to fetch your tweet stream

          http://www.flickr.com/services/api/auth.oauth.html



                                                               24
Oauth: Overview




                  25
Whoa..
•  Oauth can be overwhelming
•  But it’s great once you get to know it
•  API frameworks like django-piston
   supports Oauth out of the box




                                            26
API Frameworks?
•  API frameworks make it easier for you to
   build APIs in django
•  Tastypie
  o  http://django-tastypie.readthedocs.org/en/latest/

•  django-piston
  o  https://bitbucket.org/jespern/django-piston/wiki/Home

•  django-rest-framework
  o  http://django-rest-framework.org/

•  dj-webmachine
  o  http://benoitc.github.com/dj-webmachine/



                                                             27
django-piston
•  At PBS Education, we chose django-
   piston
  o Primarily because of its built in Oauth support
•  Original release is not actively
   maintained
•  We have modified django-piston
  o To adapt the concepts I have discussed today

           http://github.com/pbs-education/django-piston

                                                           28
Lets write some API
•  Writing API using django-piston is easy
•  Instead of writing views for your URLs,
   write handlers
•  Extend piston’s BaseHandler class
  o Override following methods:
     •  read for GET
     •  create for POST
     •  update for PUT
     •  delete for DELETE
                                             29
30
31
urls.py




          32
GET Response




               33
POST Error Response




                      34
35
Q/A?
•  Slides are available at:
  o www.codexn.com
•  Presenting a talk on API at djangocon
   2011




                                           36
utils.py




           37
auth.py




          38

More Related Content

PDF
Django rest framework tips and tricks
PDF
Intro to Web Development Using Python and Django
PPTX
REST Easy with Django-Rest-Framework
PDF
Scalable web application architecture
PDF
Create responsive websites with Django, REST and AngularJS
PDF
Introduction to Django REST Framework, an easy way to build REST framework in...
PDF
Realtime Apps with Django
KEY
Jumpstart Django
Django rest framework tips and tricks
Intro to Web Development Using Python and Django
REST Easy with Django-Rest-Framework
Scalable web application architecture
Create responsive websites with Django, REST and AngularJS
Introduction to Django REST Framework, an easy way to build REST framework in...
Realtime Apps with Django
Jumpstart Django

What's hot (20)

PPTX
Get Django, Get Hired - An opinionated guide to getting the best job, for the...
PPT
Django
PDF
Django Introduction & Tutorial
PPTX
django Forms in a Web API World
PDF
Web Development with Python and Django
ODP
Django for Beginners
PDF
Free django
PPTX
The Django Web Application Framework 2
KEY
Web application development with Django framework
PDF
A python web service
PPTX
Django Architecture Introduction
PPTX
Django Framework Overview forNon-Python Developers
PDF
Selenium&scrapy
PPTX
Best Practices for Building WordPress Applications
PDF
Django Framework and Application Structure
PDF
Modernizing WordPress Search with Elasticsearch
PDF
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
PDF
Hybrid Web Applications
PPTX
The JSON REST API for WordPress
PDF
Django Best Practices
Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Django
Django Introduction & Tutorial
django Forms in a Web API World
Web Development with Python and Django
Django for Beginners
Free django
The Django Web Application Framework 2
Web application development with Django framework
A python web service
Django Architecture Introduction
Django Framework Overview forNon-Python Developers
Selenium&scrapy
Best Practices for Building WordPress Applications
Django Framework and Application Structure
Modernizing WordPress Search with Elasticsearch
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
Hybrid Web Applications
The JSON REST API for WordPress
Django Best Practices
Ad

Viewers also liked (19)

PPT
Linux Composite Communication
PDF
Building RESTful APIs
PPTX
RESTful APIs: Promises & lies
PDF
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
ODP
Marek Kuziel - Deploying Django with Buildout
PDF
Building the Billion Dollar Landing Page with Bootstrap
PDF
Modul pelatihan-django-dasar-possupi-v1
PPTX
Secure e voting system
PDF
12 tips on Django Best Practices
PDF
Customizing the Django Admin
PPTX
Дизайн REST API для высокопроизводительных систем / Александр Лебедев (Новые ...
PDF
Linux Performance Analysis: New Tools and Old Secrets
PDF
Linux Systems Performance 2016
PPTX
Broken Linux Performance Tools 2016
PDF
BPF: Tracing and more
PDF
Velocity 2015 linux perf tools
PDF
Linux Profiling at Netflix
PDF
The Django Web Application Framework
PPTX
Secure Your REST API (The Right Way)
Linux Composite Communication
Building RESTful APIs
RESTful APIs: Promises & lies
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
Marek Kuziel - Deploying Django with Buildout
Building the Billion Dollar Landing Page with Bootstrap
Modul pelatihan-django-dasar-possupi-v1
Secure e voting system
12 tips on Django Best Practices
Customizing the Django Admin
Дизайн REST API для высокопроизводительных систем / Александр Лебедев (Новые ...
Linux Performance Analysis: New Tools and Old Secrets
Linux Systems Performance 2016
Broken Linux Performance Tools 2016
BPF: Tracing and more
Velocity 2015 linux perf tools
Linux Profiling at Netflix
The Django Web Application Framework
Secure Your REST API (The Right Way)
Ad

Similar to API Design & Security in django (20)

PDF
Facebook & Twitter API
PDF
Python Ireland Nov 2010 - RESTing with Django
PDF
What is REST?
PDF
Python RESTful webservices with Python: Flask and Django solutions
PDF
Setup API Introductie
PPTX
Best Practices for Architecting a Pragmatic Web API.
PDF
Protecting Your APIs Against Attack & Hijack
PDF
ekb.py: KISS REST API
PDF
ekbpy'2012- Юрий Юревич - Как сделать REST API на Python
PDF
Consuming RESTful services in PHP
PDF
Consuming RESTful Web services in PHP
PPTX
Django REST Framework 2022fffffffff.pptx
PPTX
RESTful Web Services
PPTX
Jones "Working with Scholarly APIs: A NISO Training Series, Session One: Foun...
PDF
Code for Startup MVP (Ruby on Rails) Session 1
PPTX
Unit 3_detailed_automotiving_mobiles.pptx
PPTX
A Deep Dive into RESTful API Design Part 2
PDF
Petr Dvořák: Mobilní webové služby pohledem iPhone developera
PDF
- Webexpo 2010
PPTX
Rest APIs Training
Facebook & Twitter API
Python Ireland Nov 2010 - RESTing with Django
What is REST?
Python RESTful webservices with Python: Flask and Django solutions
Setup API Introductie
Best Practices for Architecting a Pragmatic Web API.
Protecting Your APIs Against Attack & Hijack
ekb.py: KISS REST API
ekbpy'2012- Юрий Юревич - Как сделать REST API на Python
Consuming RESTful services in PHP
Consuming RESTful Web services in PHP
Django REST Framework 2022fffffffff.pptx
RESTful Web Services
Jones "Working with Scholarly APIs: A NISO Training Series, Session One: Foun...
Code for Startup MVP (Ruby on Rails) Session 1
Unit 3_detailed_automotiving_mobiles.pptx
A Deep Dive into RESTful API Design Part 2
Petr Dvořák: Mobilní webové služby pohledem iPhone developera
- Webexpo 2010
Rest APIs Training

More from Tareque Hossain (8)

PDF
The solr power
PDF
Life in a Queue - Using Message Queue with django
PDF
Introducing KMux - The Kernel Multiplexer
PDF
SIGTRAN - An Introduction
PPT
Django orm-tips
PPT
Django Deployment
PDF
Xen & the Art of Virtualization
PPT
Introduction to django-config
The solr power
Life in a Queue - Using Message Queue with django
Introducing KMux - The Kernel Multiplexer
SIGTRAN - An Introduction
Django orm-tips
Django Deployment
Xen & the Art of Virtualization
Introduction to django-config

Recently uploaded (20)

PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Cloud computing and distributed systems.
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Spectroscopy.pptx food analysis technology
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Electronic commerce courselecture one. Pdf
PPT
Teaching material agriculture food technology
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Big Data Technologies - Introduction.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
Cloud computing and distributed systems.
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Advanced methodologies resolving dimensionality complications for autism neur...
The AUB Centre for AI in Media Proposal.docx
Spectral efficient network and resource selection model in 5G networks
Spectroscopy.pptx food analysis technology
Unlocking AI with Model Context Protocol (MCP)
Assigned Numbers - 2025 - Bluetooth® Document
Electronic commerce courselecture one. Pdf
Teaching material agriculture food technology
Encapsulation_ Review paper, used for researhc scholars
A comparative analysis of optical character recognition models for extracting...
Chapter 3 Spatial Domain Image Processing.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
20250228 LYD VKU AI Blended-Learning.pptx
Encapsulation theory and applications.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Big Data Technologies - Introduction.pptx

API Design & Security in django

  • 1. API Design & Security in Django Tareque Hossain Education  Technology 1
  • 2. 2
  • 3. Fundamentals of API •  Architecture •  Defining resources •  Uniform response •  Serialization •  Versioning •  Authentication 3
  • 4. Your API should be RESTful •  Stateless •  Client-server •  Cacheable •  Uniform Interface o HTTP GET/POST/PUT/DELETE 4
  • 5. Defining Resources •  Resource o Cohesive set of information o Of interest to client •  Identified by URL o Uniform Resource Locator http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&photo_id=5983860647 5
  • 6. Defining Resources.. •  Resource != Django Model o May consist of data from several different model instances • Attributes • Values returned from member functions o May contain data completely unrelated to any model instance • Date & time of response 6
  • 8. Defining Resources... •  Notice how: o Each instance of book has (similar to select_related): • Authors • Editions • Awards o is_favorite indicates whether the client user has marked this book as favorite 8
  • 10. Uniform Response •  Resource attributes vary wildly •  Provide uniform response: o Include resource independent attributes • HTTP Status code • Error code (you define for your API) • Error message or data 10
  • 12. Uniform Response •  Include meta information: o Facets for certain attributes • Choices for form fields o Pagination (if applicable) • Result count • Page number • Resource per page 12
  • 13. Uniform Response •  Present in all responses (GET/POST/ PUT) •  Not in response for DELETE •  HTTP 1.1 forbids message body for 1.xx, 204 (DELETE) & 304 •  Can be parsed by client even if it can’t parse the actual resource data 13
  • 14. Serialization •  JSON rocks •  RESTful API isn’t about restrictions •  API should support: o JSONP o JSON o YAML o XML 14
  • 15. Serialization.. •  Have a default, say: JSON http://api.pbslearningmedia.org/v1.0/content/contents/cdda1ed2-da03 •  But if client requests different format, then deliver accordingly (if supported) http://api.pbslearningmedia.org/v1.0/content/contents/cdda1ed2-da03.xml 15
  • 16. Serialization.. •  Have a default, say: JSON http://api.pbslearningmedia.org/v1.0/content/contents/cdda1ed2-da03 •  But if client requests different format, then deliver accordingly (if supported) http://api.pbslearningmedia.org/v1.0/content/contents/cdda1ed2-da03.xml 16
  • 17. Versioning •  APIs change all the time o Don’t break your existing API o Roll out new API set while old ones are functioning (if data models don’t change) •  Save namespace o Old http://api.pbslearningmedia.org/v1.0/content/contents/cdda1ed2-da03 o New http://api.pbslearningmedia.org/v2.0/content/contents/cdda1ed2-da03 17
  • 18. Versioning •  Write separate URL definitions & handlers for different versions 18
  • 20. Authentication •  Not all APIs endpoints are public •  Use authentication to protect your API o Oauth is great http://wiki.oauth.net/w/page/12238551/ServiceProviders 20
  • 21. Oauth: Overview •  Two types of access: o Resource accessed by web applications directly •  User independent •  Accessing Twitter’s aggregated public timeline o Resource accessed by web applications on behalf of users • Accessing user’s private timeline 21
  • 22. Oauth: Overview •  Credentials consist of: o Consumer key & secret (application) o Access token & token secret (user) •  Each request contains: o  oauth_consumer_key o  oauth_token o  oauth_signature_method o  oauth_signature o  oauth_timestamp o  oauth_nonce o  oauth_version 22
  • 23. Oauth: 2-legged •  Resource accessed by web applications directly o Use 2-legged Oauth o Leave oauth_token empty http://oauth.googlecode.com/svn/spec/ext/consumer_request/1.0/drafts/2/spec.html 23
  • 24. Oauth: 3-legged •  Resource accessed by web applications on behalf of users o Use 3-legged Oauth o User explicitly authorizes 3rd party applications to access protected resources • Allow apps to fetch your tweet stream http://www.flickr.com/services/api/auth.oauth.html 24
  • 26. Whoa.. •  Oauth can be overwhelming •  But it’s great once you get to know it •  API frameworks like django-piston supports Oauth out of the box 26
  • 27. API Frameworks? •  API frameworks make it easier for you to build APIs in django •  Tastypie o  http://django-tastypie.readthedocs.org/en/latest/ •  django-piston o  https://bitbucket.org/jespern/django-piston/wiki/Home •  django-rest-framework o  http://django-rest-framework.org/ •  dj-webmachine o  http://benoitc.github.com/dj-webmachine/ 27
  • 28. django-piston •  At PBS Education, we chose django- piston o Primarily because of its built in Oauth support •  Original release is not actively maintained •  We have modified django-piston o To adapt the concepts I have discussed today http://github.com/pbs-education/django-piston 28
  • 29. Lets write some API •  Writing API using django-piston is easy •  Instead of writing views for your URLs, write handlers •  Extend piston’s BaseHandler class o Override following methods: •  read for GET •  create for POST •  update for PUT •  delete for DELETE 29
  • 30. 30
  • 31. 31
  • 32. urls.py 32
  • 35. 35
  • 36. Q/A? •  Slides are available at: o www.codexn.com •  Presenting a talk on API at djangocon 2011 36
  • 37. utils.py 37
  • 38. auth.py 38