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

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 StructureSEONGTAEK 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
 

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...
 
Django
DjangoDjango
Django
 
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
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 
Free django
Free djangoFree django
Free django
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django framework
 
A python web service
A python web serviceA python web service
A python web service
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture Introduction
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python Developers
 
Selenium&scrapy
Selenium&scrapySelenium&scrapy
Selenium&scrapy
 
Best Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsBest Practices for Building WordPress Applications
Best Practices for Building WordPress Applications
 
Django Framework and Application Structure
Django Framework and Application StructureDjango Framework and Application Structure
Django Framework and Application Structure
 
Modernizing WordPress Search with Elasticsearch
Modernizing WordPress Search with ElasticsearchModernizing WordPress Search with Elasticsearch
Modernizing WordPress Search with Elasticsearch
 
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...
 
Hybrid Web Applications
Hybrid Web ApplicationsHybrid Web Applications
Hybrid Web Applications
 
The JSON REST API for WordPress
The JSON REST API for WordPressThe JSON REST API for WordPress
The JSON REST API for WordPress
 
Django Best Practices
Django Best PracticesDjango Best Practices
Django Best Practices
 

Viewers also liked

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 systemMonira 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 AdminLincoln 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
 

Viewers also liked (19)

Linux Composite Communication
Linux Composite CommunicationLinux Composite Communication
Linux Composite Communication
 
Building RESTful APIs
Building RESTful APIsBuilding RESTful APIs
Building RESTful APIs
 
RESTful APIs: Promises & lies
RESTful APIs: Promises & liesRESTful APIs: Promises & lies
RESTful APIs: Promises & lies
 
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
 
Marek Kuziel - Deploying Django with Buildout
Marek Kuziel - Deploying Django with BuildoutMarek Kuziel - Deploying Django with Buildout
Marek Kuziel - Deploying Django with Buildout
 
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
 
Modul pelatihan-django-dasar-possupi-v1
Modul pelatihan-django-dasar-possupi-v1Modul pelatihan-django-dasar-possupi-v1
Modul pelatihan-django-dasar-possupi-v1
 
Secure e voting system
Secure e voting systemSecure e voting system
Secure e voting system
 
12 tips on Django Best Practices
12 tips on Django Best Practices12 tips on Django Best Practices
12 tips on Django Best Practices
 
Customizing the Django Admin
Customizing the Django AdminCustomizing the Django Admin
Customizing the Django Admin
 
Дизайн REST API для высокопроизводительных систем / Александр Лебедев (Новые ...
Дизайн REST API для высокопроизводительных систем / Александр Лебедев (Новые ...Дизайн REST API для высокопроизводительных систем / Александр Лебедев (Новые ...
Дизайн REST API для высокопроизводительных систем / Александр Лебедев (Новые ...
 
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
 
Linux Systems Performance 2016
Linux Systems Performance 2016Linux Systems Performance 2016
Linux Systems Performance 2016
 
Broken Linux Performance Tools 2016
Broken Linux Performance Tools 2016Broken Linux Performance Tools 2016
Broken Linux Performance Tools 2016
 
BPF: Tracing and more
BPF: Tracing and moreBPF: Tracing and more
BPF: Tracing and more
 
Velocity 2015 linux perf tools
Velocity 2015 linux perf toolsVelocity 2015 linux perf tools
Velocity 2015 linux perf tools
 
Linux Profiling at Netflix
Linux Profiling at NetflixLinux Profiling at Netflix
Linux Profiling at Netflix
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application Framework
 
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)
 

Similar to API Design & Security in django

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 APIYury 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 на Pythonit-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 APIsALATechSource
 
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-4577sharvari123
 
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
 

Similar to API Design & Security in django (20)

Server-side Java Programming
Server-side Java ProgrammingServer-side Java Programming
Server-side Java Programming
 
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
 
ekb.py: KISS REST API
ekb.py: KISS REST APIekb.py: KISS REST API
ekb.py: KISS REST API
 
API Docs with OpenAPI 3.0
API Docs with OpenAPI 3.0API Docs with OpenAPI 3.0
API Docs with OpenAPI 3.0
 
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
 
ekbpy'2012- Юрий Юревич - Как сделать REST API на Python
ekbpy'2012- Юрий Юревич - Как сделать REST API на Pythonekbpy'2012- Юрий Юревич - Как сделать REST API на Python
ekbpy'2012- Юрий Юревич - Как сделать REST API на Python
 
Facebook & Twitter API
Facebook & Twitter APIFacebook & Twitter API
Facebook & Twitter API
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
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
 
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
 
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
 
Decoupled Architecture and WordPress
Decoupled Architecture and WordPressDecoupled Architecture and WordPress
Decoupled Architecture and WordPress
 
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
 
Building Awesome APIs with Lumen
Building Awesome APIs with LumenBuilding Awesome APIs with Lumen
Building Awesome APIs with Lumen
 
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)
 
Создание API, которое полюбят разработчики. Глубокое погружение
Создание API, которое полюбят разработчики. Глубокое погружениеСоздание API, которое полюбят разработчики. Глубокое погружение
Создание API, которое полюбят разработчики. Глубокое погружение
 
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
 
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
 
Open Data and Web API
Open Data and Web APIOpen Data and Web API
Open Data and Web API
 
JSON API Specificiation
JSON API SpecificiationJSON API Specificiation
JSON API Specificiation
 

More from Tareque Hossain

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 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
 

More from Tareque Hossain (8)

The solr power
The solr powerThe solr power
The solr power
 
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
 
Introducing KMux - The Kernel Multiplexer
Introducing KMux - The Kernel MultiplexerIntroducing KMux - The Kernel Multiplexer
Introducing KMux - The Kernel Multiplexer
 
SIGTRAN - An Introduction
SIGTRAN - An IntroductionSIGTRAN - An Introduction
SIGTRAN - An Introduction
 
Django orm-tips
Django orm-tipsDjango orm-tips
Django orm-tips
 
Django Deployment
Django DeploymentDjango Deployment
Django Deployment
 
Xen & the Art of Virtualization
Xen & the Art of VirtualizationXen & the Art of Virtualization
Xen & the Art of Virtualization
 
Introduction to django-config
Introduction to django-configIntroduction to django-config
Introduction to django-config
 

Recently uploaded

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
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
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
 
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
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 

Recently uploaded (20)

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...
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
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...
 
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
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 

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