SlideShare uma empresa Scribd logo
1 de 38
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

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 WorldTareque Hossain
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and DjangoMichael Pirnat
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django frameworkflapiello
 
A python web service
A python web serviceA python web service
A python web serviceTemian Vlad
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture IntroductionHaiqi Chen
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersRosario Renga
 
Best Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsBest Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsTaylor 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 ElasticsearchTaylor 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 ApplicationsJames Da Costa
 
The JSON REST API for WordPress
The JSON REST API for WordPressThe JSON REST API for WordPress
The JSON REST API for WordPressTaylor Lovett
 

Mais procurados (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
 

Destaque

Linux Composite Communication
Linux Composite CommunicationLinux Composite Communication
Linux Composite CommunicationTareque Hossain
 
Building RESTful APIs
Building RESTful APIsBuilding RESTful APIs
Building RESTful APIsSilota Inc.
 
RESTful APIs: Promises & lies
RESTful APIs: Promises & liesRESTful APIs: Promises & lies
RESTful APIs: Promises & liesTareque 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 APISFernando Rocha
 
Marek Kuziel - Deploying Django with Buildout
Marek Kuziel - Deploying Django with BuildoutMarek Kuziel - Deploying Django with Buildout
Marek Kuziel - Deploying Django with Buildoutmarekkuziel
 
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 BootstrapGercek Karakus
 
Modul pelatihan-django-dasar-possupi-v1
Modul pelatihan-django-dasar-possupi-v1Modul pelatihan-django-dasar-possupi-v1
Modul pelatihan-django-dasar-possupi-v1Ridwan 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 PracticesDavid 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 SecretsBrendan Gregg
 
Linux Systems Performance 2016
Linux Systems Performance 2016Linux Systems Performance 2016
Linux Systems Performance 2016Brendan Gregg
 
Broken Linux Performance Tools 2016
Broken Linux Performance Tools 2016Broken Linux Performance Tools 2016
Broken Linux Performance Tools 2016Brendan Gregg
 
BPF: Tracing and more
BPF: Tracing and moreBPF: Tracing and more
BPF: Tracing and moreBrendan Gregg
 
Velocity 2015 linux perf tools
Velocity 2015 linux perf toolsVelocity 2015 linux perf tools
Velocity 2015 linux perf toolsBrendan Gregg
 
Linux Profiling at Netflix
Linux Profiling at NetflixLinux Profiling at Netflix
Linux Profiling at NetflixBrendan Gregg
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application FrameworkSimon 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
 

Destaque (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)
 

Semelhante a API Design & Security in django

Server-side Java Programming
Server-side Java ProgrammingServer-side Java Programming
Server-side Java ProgrammingChris 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 PlatformAntonio Peric-Mazar
 
ekb.py: KISS REST API
ekb.py: KISS REST APIekb.py: KISS REST API
ekb.py: KISS REST APIYury 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 1Henry S
 
ekbpy'2012- Юрий Юревич - Как сделать REST API на Python
ekbpy'2012- Юрий Юревич - Как сделать REST API на Pythonekbpy'2012- Юрий Юревич - Как сделать REST API на Python
ekbpy'2012- Юрий Юревич - Как сделать REST API на Pythonit-people
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna 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/2016Andre 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 APIsApigee | 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 WordPressPantheon
 
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 debateRestlet
 
Building Awesome APIs with Lumen
Building Awesome APIs with LumenBuilding Awesome APIs with Lumen
Building Awesome APIs with LumenKit 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 DevPortalsAxway
 
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 APISammy Fung
 

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

Mais de 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 djangoTareque Hossain
 
Introducing KMux - The Kernel Multiplexer
Introducing KMux - The Kernel MultiplexerIntroducing KMux - The Kernel Multiplexer
Introducing KMux - The Kernel MultiplexerTareque Hossain
 
SIGTRAN - An Introduction
SIGTRAN - An IntroductionSIGTRAN - An Introduction
SIGTRAN - An IntroductionTareque Hossain
 
Xen & the Art of Virtualization
Xen & the Art of VirtualizationXen & the Art of Virtualization
Xen & the Art of VirtualizationTareque Hossain
 
Introduction to django-config
Introduction to django-configIntroduction to django-config
Introduction to django-configTareque Hossain
 

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

Último

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 

Último (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 

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