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

What's hot (20)

Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Get Django, Get Hired - An opinionated guide to getting the best job, for the...Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Marcel Chastain
 
Django
DjangoDjango
Django
Kangjin Jun
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
之宇 趙
 
django Forms in a Web API World
django Forms in a Web API Worlddjango Forms in a Web API World
django Forms in a Web API World
Tareque Hossain
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
Michael Pirnat
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
Jason Davies
 
Free django
Free djangoFree django
Free django
Eugen Oskin
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django framework
flapiello
 
A python web service
A python web serviceA python web service
A python web service
Temian Vlad
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture Introduction
Haiqi Chen
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python Developers
Rosario Renga
 
Selenium&scrapy
Selenium&scrapySelenium&scrapy
Selenium&scrapy
Arcangelo Saracino
 
Best Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsBest Practices for Building WordPress Applications
Best Practices for Building WordPress Applications
Taylor Lovett
 
Django Framework and Application Structure
Django Framework and Application StructureDjango Framework and Application Structure
Django Framework and Application Structure
SEONGTAEK OH
 
Modernizing WordPress Search with Elasticsearch
Modernizing WordPress Search with ElasticsearchModernizing WordPress Search with Elasticsearch
Modernizing WordPress Search with Elasticsearch
Taylor Lovett
 
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
Michael Pirnat
 
Hybrid Web Applications
Hybrid Web ApplicationsHybrid Web Applications
Hybrid Web Applications
James Da Costa
 
The JSON REST API for WordPress
The JSON REST API for WordPressThe JSON REST API for WordPress
The JSON REST API for WordPress
Taylor Lovett
 
Django Best Practices
Django Best PracticesDjango Best Practices
Django Best Practices
Abdullah Çetin ÇAVDAR
 
Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Get Django, Get Hired - An opinionated guide to getting the best job, for the...Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Marcel Chastain
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
之宇 趙
 
django Forms in a Web API World
django Forms in a Web API Worlddjango Forms in a Web API World
django Forms in a Web API World
Tareque Hossain
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
Michael Pirnat
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
Jason Davies
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django framework
flapiello
 
A python web service
A python web serviceA python web service
A python web service
Temian Vlad
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture Introduction
Haiqi Chen
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python Developers
Rosario Renga
 
Best Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsBest Practices for Building WordPress Applications
Best Practices for Building WordPress Applications
Taylor Lovett
 
Django Framework and Application Structure
Django Framework and Application StructureDjango Framework and Application Structure
Django Framework and Application Structure
SEONGTAEK OH
 
Modernizing WordPress Search with Elasticsearch
Modernizing WordPress Search with ElasticsearchModernizing WordPress Search with Elasticsearch
Modernizing WordPress Search with Elasticsearch
Taylor Lovett
 
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
Michael Pirnat
 
Hybrid Web Applications
Hybrid Web ApplicationsHybrid Web Applications
Hybrid Web Applications
James Da Costa
 
The JSON REST API for WordPress
The JSON REST API for WordPressThe JSON REST API for WordPress
The JSON REST API for WordPress
Taylor Lovett
 

Viewers also liked (19)

Linux Composite Communication
Linux Composite CommunicationLinux Composite Communication
Linux Composite Communication
Tareque Hossain
 
Building RESTful APIs
Building RESTful APIsBuilding RESTful APIs
Building RESTful APIs
Silota Inc.
 
RESTful APIs: Promises & lies
RESTful APIs: Promises & liesRESTful APIs: Promises & lies
RESTful APIs: Promises & lies
Tareque Hossain
 
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APISDJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
Fernando Rocha
 
Marek Kuziel - Deploying Django with Buildout
Marek Kuziel - Deploying Django with BuildoutMarek Kuziel - Deploying Django with Buildout
Marek Kuziel - Deploying Django with Buildout
marekkuziel
 
Building the Billion Dollar Landing Page with Bootstrap
Building the Billion Dollar Landing Page with BootstrapBuilding the Billion Dollar Landing Page with Bootstrap
Building the Billion Dollar Landing Page with Bootstrap
Gercek Karakus
 
Modul pelatihan-django-dasar-possupi-v1
Modul pelatihan-django-dasar-possupi-v1Modul pelatihan-django-dasar-possupi-v1
Modul pelatihan-django-dasar-possupi-v1
Ridwan Fadjar
 
Secure e voting system
Secure e voting systemSecure e voting system
Secure e voting system
Monira Monir
 
12 tips on Django Best Practices
12 tips on Django Best Practices12 tips on Django Best Practices
12 tips on Django Best Practices
David Arcos
 
Customizing the Django Admin
Customizing the Django AdminCustomizing the Django Admin
Customizing the Django Admin
Lincoln Loop
 
Дизайн REST API для высокопроизводительных систем / Александр Лебедев (Новые ...
Дизайн REST API для высокопроизводительных систем / Александр Лебедев (Новые ...Дизайн REST API для высокопроизводительных систем / Александр Лебедев (Новые ...
Дизайн REST API для высокопроизводительных систем / Александр Лебедев (Новые ...
Ontico
 
Linux Performance Analysis: New Tools and Old Secrets
Linux Performance Analysis: New Tools and Old SecretsLinux Performance Analysis: New Tools and Old Secrets
Linux Performance Analysis: New Tools and Old Secrets
Brendan Gregg
 
Linux Systems Performance 2016
Linux Systems Performance 2016Linux Systems Performance 2016
Linux Systems Performance 2016
Brendan Gregg
 
Broken Linux Performance Tools 2016
Broken Linux Performance Tools 2016Broken Linux Performance Tools 2016
Broken Linux Performance Tools 2016
Brendan Gregg
 
BPF: Tracing and more
BPF: Tracing and moreBPF: Tracing and more
BPF: Tracing and more
Brendan Gregg
 
Velocity 2015 linux perf tools
Velocity 2015 linux perf toolsVelocity 2015 linux perf tools
Velocity 2015 linux perf tools
Brendan Gregg
 
Linux Profiling at Netflix
Linux Profiling at NetflixLinux Profiling at Netflix
Linux Profiling at Netflix
Brendan Gregg
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application Framework
Simon Willison
 
Secure Your REST API (The Right Way)
Secure Your REST API (The Right Way)Secure Your REST API (The Right Way)
Secure Your REST API (The Right Way)
Stormpath
 
Linux Composite Communication
Linux Composite CommunicationLinux Composite Communication
Linux Composite Communication
Tareque Hossain
 
Building RESTful APIs
Building RESTful APIsBuilding RESTful APIs
Building RESTful APIs
Silota Inc.
 
RESTful APIs: Promises & lies
RESTful APIs: Promises & liesRESTful APIs: Promises & lies
RESTful APIs: Promises & lies
Tareque Hossain
 
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APISDJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
Fernando Rocha
 
Marek Kuziel - Deploying Django with Buildout
Marek Kuziel - Deploying Django with BuildoutMarek Kuziel - Deploying Django with Buildout
Marek Kuziel - Deploying Django with Buildout
marekkuziel
 
Building the Billion Dollar Landing Page with Bootstrap
Building the Billion Dollar Landing Page with BootstrapBuilding the Billion Dollar Landing Page with Bootstrap
Building the Billion Dollar Landing Page with Bootstrap
Gercek Karakus
 
Modul pelatihan-django-dasar-possupi-v1
Modul pelatihan-django-dasar-possupi-v1Modul pelatihan-django-dasar-possupi-v1
Modul pelatihan-django-dasar-possupi-v1
Ridwan Fadjar
 
Secure e voting system
Secure e voting systemSecure e voting system
Secure e voting system
Monira Monir
 
12 tips on Django Best Practices
12 tips on Django Best Practices12 tips on Django Best Practices
12 tips on Django Best Practices
David Arcos
 
Customizing the Django Admin
Customizing the Django AdminCustomizing the Django Admin
Customizing the Django Admin
Lincoln Loop
 
Дизайн REST API для высокопроизводительных систем / Александр Лебедев (Новые ...
Дизайн REST API для высокопроизводительных систем / Александр Лебедев (Новые ...Дизайн REST API для высокопроизводительных систем / Александр Лебедев (Новые ...
Дизайн REST API для высокопроизводительных систем / Александр Лебедев (Новые ...
Ontico
 
Linux Performance Analysis: New Tools and Old Secrets
Linux Performance Analysis: New Tools and Old SecretsLinux Performance Analysis: New Tools and Old Secrets
Linux Performance Analysis: New Tools and Old Secrets
Brendan Gregg
 
Linux Systems Performance 2016
Linux Systems Performance 2016Linux Systems Performance 2016
Linux Systems Performance 2016
Brendan Gregg
 
Broken Linux Performance Tools 2016
Broken Linux Performance Tools 2016Broken Linux Performance Tools 2016
Broken Linux Performance Tools 2016
Brendan Gregg
 
BPF: Tracing and more
BPF: Tracing and moreBPF: Tracing and more
BPF: Tracing and more
Brendan Gregg
 
Velocity 2015 linux perf tools
Velocity 2015 linux perf toolsVelocity 2015 linux perf tools
Velocity 2015 linux perf tools
Brendan Gregg
 
Linux Profiling at Netflix
Linux Profiling at NetflixLinux Profiling at Netflix
Linux Profiling at Netflix
Brendan Gregg
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application Framework
Simon Willison
 
Secure Your REST API (The Right Way)
Secure Your REST API (The Right Way)Secure Your REST API (The Right Way)
Secure Your REST API (The Right Way)
Stormpath
 
Ad

Similar to API Design & Security in django (20)

Server-side Java Programming
Server-side Java ProgrammingServer-side Java Programming
Server-side Java Programming
Chris Schalk
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API Platform
Antonio Peric-Mazar
 
ekb.py: KISS REST API
ekb.py: KISS REST APIekb.py: KISS REST API
ekb.py: KISS REST API
Yury Yurevich
 
API Docs with OpenAPI 3.0
API Docs with OpenAPI 3.0API Docs with OpenAPI 3.0
API Docs with OpenAPI 3.0
Fabrizio Ferri-Benedetti
 
Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1
Henry S
 
ekbpy'2012- Юрий Юревич - Как сделать REST API на Python
ekbpy'2012- Юрий Юревич - Как сделать REST API на Pythonekbpy'2012- Юрий Юревич - Как сделать REST API на Python
ekbpy'2012- Юрий Юревич - Как сделать REST API на Python
it-people
 
Facebook & Twitter API
Facebook & Twitter APIFacebook & Twitter API
Facebook & Twitter API
Fabrice Delhoste
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
Lorna Mitchell
 
Maine WordPress Meetup JSON REST API, 3/16/2016
Maine WordPress Meetup JSON REST API, 3/16/2016Maine WordPress Meetup JSON REST API, 3/16/2016
Maine WordPress Meetup JSON REST API, 3/16/2016
Andre Gagnon
 
API Services: Building State-of-the-Art APIs
API Services: Building State-of-the-Art APIsAPI Services: Building State-of-the-Art APIs
API Services: Building State-of-the-Art APIs
Apigee | Google Cloud
 
Harnessing Free Content with Web Service APIs
Harnessing Free Content with Web Service APIsHarnessing Free Content with Web Service APIs
Harnessing Free Content with Web Service APIs
ALATechSource
 
Decoupled Architecture and WordPress
Decoupled Architecture and WordPressDecoupled Architecture and WordPress
Decoupled Architecture and WordPress
Pantheon
 
The never-ending REST API design debate
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debate
Restlet
 
Building Awesome APIs with Lumen
Building Awesome APIs with LumenBuilding Awesome APIs with Lumen
Building Awesome APIs with Lumen
Kit Brennan
 
Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Champaign-Urbana Javascript Meetup Talk (Jan 2020)Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Susan Potter
 
Создание API, которое полюбят разработчики. Глубокое погружение
Создание API, которое полюбят разработчики. Глубокое погружениеСоздание API, которое полюбят разработчики. Глубокое погружение
Создание API, которое полюбят разработчики. Глубокое погружение
SQALab
 
Content Strategy and Developer Engagement for DevPortals
Content Strategy and Developer Engagement for DevPortalsContent Strategy and Developer Engagement for DevPortals
Content Strategy and Developer Engagement for DevPortals
Axway
 
Connecting to-web-services-on-android-4577
Connecting to-web-services-on-android-4577Connecting to-web-services-on-android-4577
Connecting to-web-services-on-android-4577
sharvari123
 
Open Data and Web API
Open Data and Web APIOpen Data and Web API
Open Data and Web API
Sammy Fung
 
JSON API Specificiation
JSON API SpecificiationJSON API Specificiation
JSON API Specificiation
Wojciech Langiewicz
 
Server-side Java Programming
Server-side Java ProgrammingServer-side Java Programming
Server-side Java Programming
Chris Schalk
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API Platform
Antonio Peric-Mazar
 
ekb.py: KISS REST API
ekb.py: KISS REST APIekb.py: KISS REST API
ekb.py: KISS REST API
Yury Yurevich
 
Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1
Henry S
 
ekbpy'2012- Юрий Юревич - Как сделать REST API на Python
ekbpy'2012- Юрий Юревич - Как сделать REST API на Pythonekbpy'2012- Юрий Юревич - Как сделать REST API на Python
ekbpy'2012- Юрий Юревич - Как сделать REST API на Python
it-people
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
Lorna Mitchell
 
Maine WordPress Meetup JSON REST API, 3/16/2016
Maine WordPress Meetup JSON REST API, 3/16/2016Maine WordPress Meetup JSON REST API, 3/16/2016
Maine WordPress Meetup JSON REST API, 3/16/2016
Andre Gagnon
 
API Services: Building State-of-the-Art APIs
API Services: Building State-of-the-Art APIsAPI Services: Building State-of-the-Art APIs
API Services: Building State-of-the-Art APIs
Apigee | Google Cloud
 
Harnessing Free Content with Web Service APIs
Harnessing Free Content with Web Service APIsHarnessing Free Content with Web Service APIs
Harnessing Free Content with Web Service APIs
ALATechSource
 
Decoupled Architecture and WordPress
Decoupled Architecture and WordPressDecoupled Architecture and WordPress
Decoupled Architecture and WordPress
Pantheon
 
The never-ending REST API design debate
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debate
Restlet
 
Building Awesome APIs with Lumen
Building Awesome APIs with LumenBuilding Awesome APIs with Lumen
Building Awesome APIs with Lumen
Kit Brennan
 
Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Champaign-Urbana Javascript Meetup Talk (Jan 2020)Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Susan Potter
 
Создание API, которое полюбят разработчики. Глубокое погружение
Создание API, которое полюбят разработчики. Глубокое погружениеСоздание API, которое полюбят разработчики. Глубокое погружение
Создание API, которое полюбят разработчики. Глубокое погружение
SQALab
 
Content Strategy and Developer Engagement for DevPortals
Content Strategy and Developer Engagement for DevPortalsContent Strategy and Developer Engagement for DevPortals
Content Strategy and Developer Engagement for DevPortals
Axway
 
Connecting to-web-services-on-android-4577
Connecting to-web-services-on-android-4577Connecting to-web-services-on-android-4577
Connecting to-web-services-on-android-4577
sharvari123
 
Open Data and Web API
Open Data and Web APIOpen Data and Web API
Open Data and Web API
Sammy Fung
 
Ad

More from Tareque Hossain (8)

The solr power
The solr powerThe solr power
The solr power
Tareque Hossain
 
Life in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with djangoLife in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with django
Tareque Hossain
 
Introducing KMux - The Kernel Multiplexer
Introducing KMux - The Kernel MultiplexerIntroducing KMux - The Kernel Multiplexer
Introducing KMux - The Kernel Multiplexer
Tareque Hossain
 
SIGTRAN - An Introduction
SIGTRAN - An IntroductionSIGTRAN - An Introduction
SIGTRAN - An Introduction
Tareque Hossain
 
Django orm-tips
Django orm-tipsDjango orm-tips
Django orm-tips
Tareque Hossain
 
Django Deployment
Django DeploymentDjango Deployment
Django Deployment
Tareque Hossain
 
Xen & the Art of Virtualization
Xen & the Art of VirtualizationXen & the Art of Virtualization
Xen & the Art of Virtualization
Tareque Hossain
 
Introduction to django-config
Introduction to django-configIntroduction to django-config
Introduction to django-config
Tareque Hossain
 
Life in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with djangoLife in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with django
Tareque Hossain
 
Introducing KMux - The Kernel Multiplexer
Introducing KMux - The Kernel MultiplexerIntroducing KMux - The Kernel Multiplexer
Introducing KMux - The Kernel Multiplexer
Tareque Hossain
 
SIGTRAN - An Introduction
SIGTRAN - An IntroductionSIGTRAN - An Introduction
SIGTRAN - An Introduction
Tareque Hossain
 
Xen & the Art of Virtualization
Xen & the Art of VirtualizationXen & the Art of Virtualization
Xen & the Art of Virtualization
Tareque Hossain
 
Introduction to django-config
Introduction to django-configIntroduction to django-config
Introduction to django-config
Tareque Hossain
 

Recently uploaded (20)

Microsoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentationMicrosoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentation
Digitalmara
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
The case for on-premises AI
The case for on-premises AIThe case for on-premises AI
The case for on-premises AI
Principled Technologies
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Peter Bittner
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
Create Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent BuilderCreate Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent Builder
DianaGray10
 
Introducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and ARIntroducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and AR
Safe Software
 
Microsoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentationMicrosoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentation
Digitalmara
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Peter Bittner
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
Create Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent BuilderCreate Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent Builder
DianaGray10
 
Introducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and ARIntroducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and AR
Safe Software
 

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