SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoKnoldus Inc.
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaEdureka!
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Introduction to github slideshare
Introduction to github slideshareIntroduction to github slideshare
Introduction to github slideshareRakesh Sukumar
 
NextJS, A JavaScript Framework for building next generation SPA
NextJS, A JavaScript Framework for building next generation SPA  NextJS, A JavaScript Framework for building next generation SPA
NextJS, A JavaScript Framework for building next generation SPA Pramendra Gupta
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkMarcel Chastain
 
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!
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN StackTroy Miles
 
React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXLRob Gietema
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3 ArezooKmn
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 
Introducing GitLab (September 2018)
Introducing GitLab (September 2018)Introducing GitLab (September 2018)
Introducing GitLab (September 2018)Noa Harel
 
Developing Faster with Swagger
Developing Faster with SwaggerDeveloping Faster with Swagger
Developing Faster with SwaggerTony Tam
 

Was ist angesagt? (20)

Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Introduction to github slideshare
Introduction to github slideshareIntroduction to github slideshare
Introduction to github slideshare
 
NextJS, A JavaScript Framework for building next generation SPA
NextJS, A JavaScript Framework for building next generation SPA  NextJS, A JavaScript Framework for building next generation SPA
NextJS, A JavaScript Framework for building next generation SPA
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
 
Restful api
Restful apiRestful api
Restful api
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
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...
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXL
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
React
React React
React
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
Introducing GitLab (September 2018)
Introducing GitLab (September 2018)Introducing GitLab (September 2018)
Introducing GitLab (September 2018)
 
Developing Faster with Swagger
Developing Faster with SwaggerDeveloping Faster with Swagger
Developing Faster with Swagger
 

Andere mochten auch

Como organizar projetos em django
Como organizar projetos em djangoComo organizar projetos em django
Como organizar projetos em djangoLuiz Sotero
 
Rest apis with DRF
Rest apis with DRFRest apis with DRF
Rest apis with DRFDharmit Shah
 
Building a custom cms with django
Building a custom cms with djangoBuilding a custom cms with django
Building a custom cms with djangoYann Malet
 
A python web service
A python web serviceA python web service
A python web serviceTemian Vlad
 
Django rest framework tips and tricks
Django rest framework   tips and tricksDjango rest framework   tips and tricks
Django rest framework tips and tricksxordoquy
 
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 FrameworkLoad 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 sqlbchesneau
 
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 solutionsSolution4Future
 
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 OdooHassan 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 AngularJSHannes 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 androidBosco 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 frameworkBleemeo
 
Cours python avancé
Cours python avancéCours python avancé
Cours python avancépierrepo
 

Andere mochten auch (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
 

Ähnlich wie 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 1Henry 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 2009Jason Davies
 
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 DrillCharles Givre
 
[DLHacks]Introduction to ChainerCV
[DLHacks]Introduction to ChainerCV[DLHacks]Introduction to ChainerCV
[DLHacks]Introduction to ChainerCVDeep 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 PlatformAntonio Peric-Mazar
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna 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 WebAPIGert Drapers
 
Icinga 2009 at OSMC
Icinga 2009 at OSMCIcinga 2009 at OSMC
Icinga 2009 at OSMCIcinga
 
Lessons learned while building Omroep.nl
Lessons learned while building Omroep.nlLessons learned while building Omroep.nl
Lessons learned while building Omroep.nlbartzon
 
Ei cakephp
Ei cakephpEi cakephp
Ei cakephpeiei lay
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and ActivatorKevin Webber
 

Ähnlich wie 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
 
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
 
Ei cakephp
Ei cakephpEi cakephp
Ei cakephp
 
Cakeph pppt
Cakeph ppptCakeph pppt
Cakeph pppt
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and Activator
 

Kürzlich hochgeladen

WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 

Kürzlich hochgeladen (20)

WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 

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