SlideShare a Scribd company logo
Building an API with Django and
Django REST Framework
PyTennessee 2016
2
Hi, I’m Chris Foresman
• Senior Systems Engineer at Vokal
• Python mentor to all ages
• Learned to program in BASIC on a
TRS-80 circa 1986
• Love: karaoke, bourbon, brunch
• I have a 3-yr-old at home
@foresmac
3
Hi, I’m Adam Bain
• Systems Engineer at Vokal
• Rehabilitated Java engineer via
Python
• Learned to program in BASIC circa
94
• Likes: Hockey, Craft Beer
• I referee robotics competitions
@adam_bain
4
Let’s build an API!
5
With Python!
6
Who’s with us so far?
7
If you want to follow along:
• terminal access
• a text editor: SublimeText, Atom, vim
• or IDE, like PyCharm
• ideally have virtualenv (or venv)
• git
8
If you want to follow along:
• mkdir ~/tutorial
• virtualenv ~/tutorial
• cd ~/tutorial
• source bin/activate
• pip install django djangorestframework
• git clone https://github.com/vokal/deckbuilder-api.git
• git checkout -b base base
9
Ok, let’s get started.
10
Planning
11
Planning
• sketch out your data models
• how will different things be represented?
• think about what actions your API needs to support
• will you be strictly RESTful, supporting only CRUD?
• or, will your API be more expressive?
• it’s up to you to strike a balance!
12
Wait, isn’t CRUD bad? And why do
I need REST already?
13
CRUD
• your basic database operations:
• CREATE
• READ
• UPDATE
• DELETE
14
HTTP
• your basic HTTP request methods:
• POST
• GET
• PUT (and/or PATCH)
• DELETE
15
REST in a nutshell
• your basic RESTful API:
• CREATE = POST
• READ = GET
• UPDATE = PUT (and/or PATCH)
• DELETE = DELETE
FYI: REST stands for Representational State Transfer
16
Common RESTful pattern
• /object
• POST data to this endpoint to create a new object
• GET this endpoint to retrieve a list of objects
• /object/:id
• GET this endpoint to get details about a particular object
• PUT or PATCH data to this endpoint to update that object
• DELETE this endpoint to delete the object
17
Pragmatic, not-strictly-RESTful patterns
• /object/:id/action
• Either POST data to this endpoint to perform some action,
particularly if it results in new data being created, or
• PUT to this endpoint to perform some action that doesn’t require
any additional data, and typically modifies existing data but does
not create new data objects
• /object/noun
• GET this endpoint to get some specific grouping or set of the
objects
18
Be as logically consistent as
humanly possible
19
Models
git checkout -b models models
20
Models
• define objects that represent your data
• map fields to database column types
• handle DB magic for you (for the most part)
• strive for “fat” models and “thin” views
• give your models methods
• for complicated creation, updating, etc, use managers
21
Models
• know your field types
• CharField
• IntegerField
• BooleanField
• DatetimeField
• etc
• fields also have parameters that affect database table creation
and data validation
• null=True, max_length=255, etc
22
Serializers
git checkout -b serializers serializers
23
Serializers
• this is the main gateway between your API and the world
• typically:
• validates input
• converts JSON to Python dict
• converts model instances to Python dicts
• which can then be passed to model instances and saved to the
database
24
Generic Views
git checkout -b generic_view generic_view
25
Generic Views
• class-based views
• can be configured with basic attributes:
• serializer
• permissions_classes
• queryset
• or can use more dynamic config:
• get_queryset()
• get_serializer()
• etc
26
Generic Views
• basic GenericAPIView
• composable with mixins
• most common options pre-defined:
• ListCreateView
• RetrieveUpdateDestroyView
• others...
27
View Sets
git checkout -b view_set view_set
28
View Sets
• great for straightforward CRUD operations
• can be extended with additional “detail” views
• automagically handle URL routing generation
• a lot of functionality for a little bit of code
29
URL Routing
30
URL Routing
• just match a URL regex with a corresponding view
• call as_view() on it, like so:
url(r’^/card/?$’,
ListCreateCardView.as_view(),
name=’list-create-card’)
31
URL Routing
• if you’re using ViewSets, do the following:
router = routers.DefaultRouter()
router.register(r'card', CardViewSet)
urlpatterns = router.urls
32
“Browsable” API
git checkout -b browsable_api browsable_api
33
“Browseable” API
• Let’s you experiment with your API via a browser
34
Testing
35
Testing
• why does everyone hate it?
• trust us, you’ll thank yourself later
• generally “integration” tests cover most code
• additional unit tests cover everything else
• for Pete’s sake, learn to use mock
36
You’ve got questions?
37
We’ve got answers.
38
(Hopefully)
39
Resources
• http://www.django-rest-framework.org
• https://docs.djangoproject.com
• https://virtualenv.readthedocs.org
• https://github.com/vokal/deckbuilder-api
Thank you!
PyTennessee 2016

More Related Content

What's hot

Angular tutorial
Angular tutorialAngular tutorial
Angular tutorial
Rohit Gupta
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
Angular js PPT
Angular js PPTAngular js PPT
Angular js PPT
Imtiyaz Ahmad Khan
 
An Introduction to Vuejs
An Introduction to VuejsAn Introduction to Vuejs
An Introduction to Vuejs
Paddy Lock
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
Marcel Chastain
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
Hassan Dar
 
Laravel Introduction
Laravel IntroductionLaravel Introduction
Laravel Introduction
Ahmad Shah Hafizan Hamidin
 
Intro to React
Intro to ReactIntro to React
Intro to React
Justin Reock
 
Introduction to Django Rest Framework
Introduction to Django Rest FrameworkIntroduction to Django Rest Framework
Introduction to Django Rest Framework
bangaloredjangousergroup
 
Bootstrap PPT Part - 2
Bootstrap PPT Part - 2Bootstrap PPT Part - 2
Bootstrap PPT Part - 2
EPAM Systems
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
Varun Raj
 
Django Rest Framework | How to Create a RESTful API Using Django | Django Tut...
Django Rest Framework | How to Create a RESTful API Using Django | Django Tut...Django Rest Framework | How to Create a RESTful API Using Django | Django Tut...
Django Rest Framework | How to Create a RESTful API Using Django | Django Tut...
Edureka!
 
Bootstrap PPT by Mukesh
Bootstrap PPT by MukeshBootstrap PPT by Mukesh
Bootstrap PPT by Mukesh
Mukesh Kumar
 
PHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and SessionsPHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and Sessions
Vibrant Technologies & Computers
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
AnmolPandita7
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
CSS3 Media Queries
CSS3 Media QueriesCSS3 Media Queries
CSS3 Media Queries
Russ Weakley
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 

What's hot (20)

Angular tutorial
Angular tutorialAngular tutorial
Angular tutorial
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
Angular js PPT
Angular js PPTAngular js PPT
Angular js PPT
 
An Introduction to Vuejs
An Introduction to VuejsAn Introduction to Vuejs
An Introduction to Vuejs
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
Laravel Introduction
Laravel IntroductionLaravel Introduction
Laravel Introduction
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Introduction to Django Rest Framework
Introduction to Django Rest FrameworkIntroduction to Django Rest Framework
Introduction to Django Rest Framework
 
Bootstrap PPT Part - 2
Bootstrap PPT Part - 2Bootstrap PPT Part - 2
Bootstrap PPT Part - 2
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
Django Rest Framework | How to Create a RESTful API Using Django | Django Tut...
Django Rest Framework | How to Create a RESTful API Using Django | Django Tut...Django Rest Framework | How to Create a RESTful API Using Django | Django Tut...
Django Rest Framework | How to Create a RESTful API Using Django | Django Tut...
 
Bootstrap PPT by Mukesh
Bootstrap PPT by MukeshBootstrap PPT by Mukesh
Bootstrap PPT by Mukesh
 
PHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and SessionsPHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and Sessions
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
CSS3 Media Queries
CSS3 Media QueriesCSS3 Media Queries
CSS3 Media Queries
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 

Viewers also liked

Como organizar projetos em django
Como organizar projetos em djangoComo organizar projetos em django
Como organizar projetos em django
Luiz Sotero
 
Rest apis with DRF
Rest apis with DRFRest apis with DRF
Rest apis with DRF
Dharmit Shah
 
Building a custom cms with django
Building a custom cms with djangoBuilding a custom cms with django
Building a custom cms with django
Yann Malet
 
Django by mrjmad
Django by mrjmadDjango by mrjmad
Django by mrjmad
Jean-Michel ARMAND
 
Free django
Free djangoFree django
Free django
Eugen Oskin
 
A python web service
A python web serviceA python web service
A python web service
Temian Vlad
 
Django rest framework tips and tricks
Django rest framework   tips and tricksDjango rest framework   tips and tricks
Django rest framework tips and tricks
xordoquy
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
Eric Palakovich Carr
 
Django REST Framework
Django REST FrameworkDjango REST Framework
Django REST Framework
Load Impact
 
Python et les bases de données non sql
Python et les bases de données non sqlPython et les bases de données non sql
Python et les bases de données non sql
bchesneau
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
Python et son intégration avec Odoo
Python et son intégration avec OdooPython et son intégration avec Odoo
Python et son intégration avec Odoo
Hassan WAHSISS
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJS
Hannes Hapke
 
Débuter avec phonegap (APACHE CORDOVA) dans eclipse pour android
Débuter avec phonegap (APACHE CORDOVA) dans eclipse pour androidDébuter avec phonegap (APACHE CORDOVA) dans eclipse pour android
Débuter avec phonegap (APACHE CORDOVA) dans eclipse pour android
Bosco Basabana
 
Créer une api publique avec Django REST framework
Créer une api publique avec Django REST frameworkCréer une api publique avec Django REST framework
Créer une api publique avec Django REST framework
Bleemeo
 
Cours python avancé
Cours python avancéCours python avancé
Cours python avancépierrepo
 
Apache Cordova 3.3 de zéro
Apache Cordova 3.3 de zéroApache Cordova 3.3 de zéro
Apache Cordova 3.3 de zéro
Alexandre Pereira
 

Viewers also liked (17)

Como organizar projetos em django
Como organizar projetos em djangoComo organizar projetos em django
Como organizar projetos em django
 
Rest apis with DRF
Rest apis with DRFRest apis with DRF
Rest apis with DRF
 
Building a custom cms with django
Building a custom cms with djangoBuilding a custom cms with django
Building a custom cms with django
 
Django by mrjmad
Django by mrjmadDjango by mrjmad
Django by mrjmad
 
Free django
Free djangoFree django
Free django
 
A python web service
A python web serviceA python web service
A python web service
 
Django rest framework tips and tricks
Django rest framework   tips and tricksDjango rest framework   tips and tricks
Django rest framework tips and tricks
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Django REST Framework
Django REST FrameworkDjango REST Framework
Django REST Framework
 
Python et les bases de données non sql
Python et les bases de données non sqlPython et les bases de données non sql
Python et les bases de données non sql
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
Python et son intégration avec Odoo
Python et son intégration avec OdooPython et son intégration avec Odoo
Python et son intégration avec Odoo
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJS
 
Débuter avec phonegap (APACHE CORDOVA) dans eclipse pour android
Débuter avec phonegap (APACHE CORDOVA) dans eclipse pour androidDébuter avec phonegap (APACHE CORDOVA) dans eclipse pour android
Débuter avec phonegap (APACHE CORDOVA) dans eclipse pour android
 
Créer une api publique avec Django REST framework
Créer une api publique avec Django REST frameworkCréer une api publique avec Django REST framework
Créer une api publique avec Django REST framework
 
Cours python avancé
Cours python avancéCours python avancé
Cours python avancé
 
Apache Cordova 3.3 de zéro
Apache Cordova 3.3 de zéroApache Cordova 3.3 de zéro
Apache Cordova 3.3 de zéro
 

Similar to Building an API with Django and Django REST Framework

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
 
CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009
Jason Davies
 
Introduction to Monsoon PHP framework
Introduction to Monsoon PHP frameworkIntroduction to Monsoon PHP framework
Introduction to Monsoon PHP framework
Krishna Srikanth Manda
 
Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']
Jan Helke
 
Rapid API Development ArangoDB Foxx
Rapid API Development ArangoDB FoxxRapid API Development ArangoDB Foxx
Rapid API Development ArangoDB FoxxMichael Hackstein
 
Drilling Cyber Security Data With Apache Drill
Drilling Cyber Security Data With Apache DrillDrilling Cyber Security Data With Apache Drill
Drilling Cyber Security Data With Apache Drill
Charles Givre
 
Introduction to Git and Github
Introduction to Git and GithubIntroduction to Git and Github
Introduction to Git and Github
Roland Emmanuel Salunga
 
[DLHacks]Introduction to ChainerCV
[DLHacks]Introduction to ChainerCV[DLHacks]Introduction to ChainerCV
[DLHacks]Introduction to ChainerCV
Deep Learning JP
 
Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)
Igalia
 
(ATS6-PLAT04) Query service
(ATS6-PLAT04) Query service (ATS6-PLAT04) Query service
(ATS6-PLAT04) Query service
BIOVIA
 
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
 
Data-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptxData-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptx
DRSHk10
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
Lorna Mitchell
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
Lorna Mitchell
 
Practical introduction to dev ops with chef
Practical introduction to dev ops with chefPractical introduction to dev ops with chef
Practical introduction to dev ops with chefLeanDog
 
Building RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPIBuilding RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPI
Gert Drapers
 
Icinga 2009 at OSMC
Icinga 2009 at OSMCIcinga 2009 at OSMC
Icinga 2009 at OSMC
Icinga
 
Lessons learned while building Omroep.nl
Lessons learned while building Omroep.nlLessons learned while building Omroep.nl
Lessons learned while building Omroep.nlbartzon
 
Cakeph pppt
Cakeph ppptCakeph pppt
Cakeph pppt
Wizard Rider
 
Ei cakephp
Ei cakephpEi cakephp
Ei cakephp
eiei lay
 

Similar to Building an API with Django and Django REST Framework (20)

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
 
CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009
 
Introduction to Monsoon PHP framework
Introduction to Monsoon PHP frameworkIntroduction to Monsoon PHP framework
Introduction to Monsoon PHP framework
 
Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']
 
Rapid API Development ArangoDB Foxx
Rapid API Development ArangoDB FoxxRapid API Development ArangoDB Foxx
Rapid API Development ArangoDB Foxx
 
Drilling Cyber Security Data With Apache Drill
Drilling Cyber Security Data With Apache DrillDrilling Cyber Security Data With Apache Drill
Drilling Cyber Security Data With Apache Drill
 
Introduction to Git and Github
Introduction to Git and GithubIntroduction to Git and Github
Introduction to Git and Github
 
[DLHacks]Introduction to ChainerCV
[DLHacks]Introduction to ChainerCV[DLHacks]Introduction to ChainerCV
[DLHacks]Introduction to ChainerCV
 
Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)
 
(ATS6-PLAT04) Query service
(ATS6-PLAT04) Query service (ATS6-PLAT04) Query service
(ATS6-PLAT04) Query service
 
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
 
Data-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptxData-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptx
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Practical introduction to dev ops with chef
Practical introduction to dev ops with chefPractical introduction to dev ops with chef
Practical introduction to dev ops with chef
 
Building RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPIBuilding RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPI
 
Icinga 2009 at OSMC
Icinga 2009 at OSMCIcinga 2009 at OSMC
Icinga 2009 at OSMC
 
Lessons learned while building Omroep.nl
Lessons learned while building Omroep.nlLessons learned while building Omroep.nl
Lessons learned while building Omroep.nl
 
Cakeph pppt
Cakeph ppptCakeph pppt
Cakeph pppt
 
Ei cakephp
Ei cakephpEi cakephp
Ei cakephp
 

Recently uploaded

2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 

Recently uploaded (20)

2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 

Building an API with Django and Django REST Framework

  • 1. Building an API with Django and Django REST Framework PyTennessee 2016
  • 2. 2 Hi, I’m Chris Foresman • Senior Systems Engineer at Vokal • Python mentor to all ages • Learned to program in BASIC on a TRS-80 circa 1986 • Love: karaoke, bourbon, brunch • I have a 3-yr-old at home @foresmac
  • 3. 3 Hi, I’m Adam Bain • Systems Engineer at Vokal • Rehabilitated Java engineer via Python • Learned to program in BASIC circa 94 • Likes: Hockey, Craft Beer • I referee robotics competitions @adam_bain
  • 7. 7 If you want to follow along: • terminal access • a text editor: SublimeText, Atom, vim • or IDE, like PyCharm • ideally have virtualenv (or venv) • git
  • 8. 8 If you want to follow along: • mkdir ~/tutorial • virtualenv ~/tutorial • cd ~/tutorial • source bin/activate • pip install django djangorestframework • git clone https://github.com/vokal/deckbuilder-api.git • git checkout -b base base
  • 9. 9 Ok, let’s get started.
  • 11. 11 Planning • sketch out your data models • how will different things be represented? • think about what actions your API needs to support • will you be strictly RESTful, supporting only CRUD? • or, will your API be more expressive? • it’s up to you to strike a balance!
  • 12. 12 Wait, isn’t CRUD bad? And why do I need REST already?
  • 13. 13 CRUD • your basic database operations: • CREATE • READ • UPDATE • DELETE
  • 14. 14 HTTP • your basic HTTP request methods: • POST • GET • PUT (and/or PATCH) • DELETE
  • 15. 15 REST in a nutshell • your basic RESTful API: • CREATE = POST • READ = GET • UPDATE = PUT (and/or PATCH) • DELETE = DELETE FYI: REST stands for Representational State Transfer
  • 16. 16 Common RESTful pattern • /object • POST data to this endpoint to create a new object • GET this endpoint to retrieve a list of objects • /object/:id • GET this endpoint to get details about a particular object • PUT or PATCH data to this endpoint to update that object • DELETE this endpoint to delete the object
  • 17. 17 Pragmatic, not-strictly-RESTful patterns • /object/:id/action • Either POST data to this endpoint to perform some action, particularly if it results in new data being created, or • PUT to this endpoint to perform some action that doesn’t require any additional data, and typically modifies existing data but does not create new data objects • /object/noun • GET this endpoint to get some specific grouping or set of the objects
  • 18. 18 Be as logically consistent as humanly possible
  • 19. 19 Models git checkout -b models models
  • 20. 20 Models • define objects that represent your data • map fields to database column types • handle DB magic for you (for the most part) • strive for “fat” models and “thin” views • give your models methods • for complicated creation, updating, etc, use managers
  • 21. 21 Models • know your field types • CharField • IntegerField • BooleanField • DatetimeField • etc • fields also have parameters that affect database table creation and data validation • null=True, max_length=255, etc
  • 22. 22 Serializers git checkout -b serializers serializers
  • 23. 23 Serializers • this is the main gateway between your API and the world • typically: • validates input • converts JSON to Python dict • converts model instances to Python dicts • which can then be passed to model instances and saved to the database
  • 24. 24 Generic Views git checkout -b generic_view generic_view
  • 25. 25 Generic Views • class-based views • can be configured with basic attributes: • serializer • permissions_classes • queryset • or can use more dynamic config: • get_queryset() • get_serializer() • etc
  • 26. 26 Generic Views • basic GenericAPIView • composable with mixins • most common options pre-defined: • ListCreateView • RetrieveUpdateDestroyView • others...
  • 27. 27 View Sets git checkout -b view_set view_set
  • 28. 28 View Sets • great for straightforward CRUD operations • can be extended with additional “detail” views • automagically handle URL routing generation • a lot of functionality for a little bit of code
  • 30. 30 URL Routing • just match a URL regex with a corresponding view • call as_view() on it, like so: url(r’^/card/?$’, ListCreateCardView.as_view(), name=’list-create-card’)
  • 31. 31 URL Routing • if you’re using ViewSets, do the following: router = routers.DefaultRouter() router.register(r'card', CardViewSet) urlpatterns = router.urls
  • 32. 32 “Browsable” API git checkout -b browsable_api browsable_api
  • 33. 33 “Browseable” API • Let’s you experiment with your API via a browser
  • 35. 35 Testing • why does everyone hate it? • trust us, you’ll thank yourself later • generally “integration” tests cover most code • additional unit tests cover everything else • for Pete’s sake, learn to use mock
  • 39. 39 Resources • http://www.django-rest-framework.org • https://docs.djangoproject.com • https://virtualenv.readthedocs.org • https://github.com/vokal/deckbuilder-api