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

PPTX
Angular
Mouad EL Fakir
 
PPT
Introduction to the Web API
Brad Genereaux
 
PPTX
Spring MVC
Emprovise
 
PPTX
Introduction to Django Rest Framework
bangaloredjangousergroup
 
PPSX
Rest api standards and best practices
Ankita Mahajan
 
PPTX
A Brief Introduction to React.js
Doug Neiner
 
PDF
OpenAPI and gRPC Side by-Side
Tim Burks
 
PDF
React Js Simplified
Sunil Yadav
 
PDF
React js
Rajesh Kolla
 
PDF
REST API and CRUD
Prem Sanil
 
PDF
What is REST API? REST API Concepts and Examples | Edureka
Edureka!
 
PPTX
Angular 14.pptx
MohaNedGhawar
 
PDF
React – ¿Qué es React.js?
Gorka Magaña
 
PDF
APIs, REST e RESTful: O que os programadores precisam saber? - Marcos Echevar...
Tchelinux
 
PDF
Angular - Chapter 1 - Introduction
WebStackAcademy
 
PDF
PHP, the GraphQL ecosystem and GraphQLite
JEAN-GUILLAUME DUJARDIN
 
PPTX
REST API
Tofazzal Ahmed
 
PPTX
Introduction to Spring Boot
Purbarun Chakrabarti
 
PPTX
Django Framework Overview forNon-Python Developers
Rosario Renga
 
PPTX
Spring Boot Tutorial
Naphachara Rattanawilai
 
Introduction to the Web API
Brad Genereaux
 
Spring MVC
Emprovise
 
Introduction to Django Rest Framework
bangaloredjangousergroup
 
Rest api standards and best practices
Ankita Mahajan
 
A Brief Introduction to React.js
Doug Neiner
 
OpenAPI and gRPC Side by-Side
Tim Burks
 
React Js Simplified
Sunil Yadav
 
React js
Rajesh Kolla
 
REST API and CRUD
Prem Sanil
 
What is REST API? REST API Concepts and Examples | Edureka
Edureka!
 
Angular 14.pptx
MohaNedGhawar
 
React – ¿Qué es React.js?
Gorka Magaña
 
APIs, REST e RESTful: O que os programadores precisam saber? - Marcos Echevar...
Tchelinux
 
Angular - Chapter 1 - Introduction
WebStackAcademy
 
PHP, the GraphQL ecosystem and GraphQLite
JEAN-GUILLAUME DUJARDIN
 
REST API
Tofazzal Ahmed
 
Introduction to Spring Boot
Purbarun Chakrabarti
 
Django Framework Overview forNon-Python Developers
Rosario Renga
 
Spring Boot Tutorial
Naphachara Rattanawilai
 

Viewers also liked (17)

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

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

PPTX
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Caktus Group
 
PPTX
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Caktus Group
 
PDF
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Inexture Solutions
 
PDF
Building RESTful APIs
Silota Inc.
 
PDF
Django Rest Framework - Building a Web API
Marcos Pereira
 
PPTX
Super simple introduction to REST-APIs (2nd version)
Patrick Savalle
 
PDF
Django Restful Web Services Gaston C Hillar
suilahvrieze
 
PDF
UnRESTful APIs with Django
Ari Lacenski
 
PDF
22 REST & JSON API Design #burningkeyboards
Denis Ristic
 
PDF
FastAPI - Rest Architecture - in english.pdf
inigraha
 
PDF
Rest api with Python
Santosh Ghimire
 
PDF
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
Max Klymyshyn
 
PPTX
Django REST Framework 2022fffffffff.pptx
ThirzaAhmadTsaqif
 
PPTX
Http and REST APIs.
Rahul Tanwani
 
PPTX
REST-API introduction for developers
Patrick Savalle
 
PDF
REST APIs
Arthur De Magalhaes
 
PPTX
React django
Heber Silva
 
PDF
Python Ireland Nov 2010 - RESTing with Django
Python Ireland
 
PDF
API Design & Security in django
Tareque Hossain
 
PDF
Panoramic view of web APIs
Karen Immanuel
 
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Caktus Group
 
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Caktus Group
 
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Inexture Solutions
 
Building RESTful APIs
Silota Inc.
 
Django Rest Framework - Building a Web API
Marcos Pereira
 
Super simple introduction to REST-APIs (2nd version)
Patrick Savalle
 
Django Restful Web Services Gaston C Hillar
suilahvrieze
 
UnRESTful APIs with Django
Ari Lacenski
 
22 REST & JSON API Design #burningkeyboards
Denis Ristic
 
FastAPI - Rest Architecture - in english.pdf
inigraha
 
Rest api with Python
Santosh Ghimire
 
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
Max Klymyshyn
 
Django REST Framework 2022fffffffff.pptx
ThirzaAhmadTsaqif
 
Http and REST APIs.
Rahul Tanwani
 
REST-API introduction for developers
Patrick Savalle
 
React django
Heber Silva
 
Python Ireland Nov 2010 - RESTing with Django
Python Ireland
 
API Design & Security in django
Tareque Hossain
 
Panoramic view of web APIs
Karen Immanuel
 
Ad

Recently uploaded (20)

PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 

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