SlideShare une entreprise Scribd logo
1  sur  33
Write an API for Almost Anything
DjangoCon 2017
The Amazing Power and Flexibility of
Django Rest Framework
Who Am I?
●Web Developer at Caktus Group
●Organizer of PyLadies RDU
●Builder and User of APIs
Note: Slides available at:
http://cakt.us/DjangoCon2017talk
What does “API” mean, anyway?
● “Application Programming Interface”
● Definition (techtarget.com): “An application program
interface (API) is
code that allows two software programs to
communicate with each other.”
Why Are APIs Useful?
●Flexibility
●Access (internally and externally)
●Future-proofing
Example: Customized Output
●Massage therapist needed schedule
information to be sharable without client
information
●Scheduling software did not do this
○But did have an API!
Example: Customized Output
●Small script can pull schedule information
and post without client information to a
shareable calendar
●API made it possible to create an otherwise
nonexistent feature
APIs for Non-Web Applications
●Easy and practical enough to be useful for
other distributed applications
●Example: Game back-end
○https://github.com/flowerncsu/ecgc-2017
Internal Separation
●Dynamic, highly interactive pages require
JavaScript
●Use API to separate Django code from
JavaScript code
Internal Separation
●Cleaner code
●Easier to use JS frameworks
●Retrieve data and context with simple
requests
APIs Are Awesome, So
How Do I Build One?
Building an API
●Many ways, many packages
●Django Rest Framework
○Sits nicely on top of existing Django code
○Very thorough feature set
Anatomy of Django Rest Framework
API
Router
ViewSet
Serializer
Django Models/
Database
serializers.py
views.py
urls.py
Anatomy of Django Rest Framework
API
Serializer
Django Models/
Database
Building the Serializer
from rest_framework import serializers
from .models import MyModel
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = (
'id',
'name',
'category',
)
Anatomy of Django Rest Framework
API
ViewSet
Serializer
Django Models/
Database
Building the ViewSet
from rest_framework import viewsets
from .models import MyModel
from .serializers import MyModelSerializer
class MyModelViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows MyModel instances
to be viewed or edited.
"""
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
Anatomy of Django Rest Framework
API
Router
ViewSet
Serializer
Django Models/
Database
Building URLs with the Router
from django.conf.urls import url, include
from rest_framework import routers
from myapp import views as myapp_api
router = routers.DefaultRouter()
router.register(r'mymodel', myapp_api.MyModelViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework'))
]
Accessing the API
HTTP Methods Operations
●C
●R
●U
●D
Accessing the API
HTTP Methods
● POST
Operations
●Create
●R
●U
●D
Accessing the API
HTTP Methods
● POST
● GET
Operations
●Create
●Read
●U
●D
Accessing the API
HTTP Methods
● POST
● GET
● PUT
● PATCH
Operations
●Create
●Read
●Update
●D
Accessing the API
HTTP Methods
● POST
● GET
● PUT
● PATCH
● DELETE
Operations
●Create
●Read
●Update
●Delete
Accessing the API
HTTP Methods
● POST
● GET
● PUT
● PATCH
● DELETE
Operations
●Create
●Read
●Update
●Delete
Accessing the API
router.register(r'mymodel', myapp_api.MyModelViewSet)
(GET) myapp.com/mymodel
-> List of instances, fields based on serializer
(POST) myapp.com/mymodel
-> Create a new instance
(GET) myapp.com/mymodel/instance_id
-> Get details for instance with instance_id
(DELETE) myapp.com/mymodel/instance_id
-> Delete instance with instance_id
More information:
http://www.django-rest-framework.org/api-guide/viewsets/
What If I Don’t Want Users Doing That?
Several options to protect data:
●Authentication
●Read-only Viewsets
●Restricting specific actions
Documentation
●Key to usability of the API
●Structure is predictable
○URL and HTTP method
○Operation performed at that URL/method
○Parameters expected
○Data format returned
More information:
http://www.django-rest-framework.org/topics/documenting-your-api/
Automatic Documentation
from rest_framework.documentation import include_docs_urls
...
urlpatterns = [
...
url(r'^docs/', include_docs_urls(title='My API'))
]
More information:
http://www.django-rest-framework.org/topics/documenting-your-api/
Tests
● API functionality can be tested simply
●Automated tests mean “set it and forget it”
●Test failures can highlight changes that
should be reflected in documentation
Sample Test
from rest_framework.test import APITestCase
class TestMyModelViewSet(APITestCase):
def setUp(self):
self.url = reverse('mymodel-list')
self.instances = [MyModel() for i in range(3)]
for item in self.instances:
item.save()
def test_list_view(self):
response = self.client.get(self.url, format='json')
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.data), 3)
More information:
http://www.django-rest-framework.org/api-guide/testing/
Sample Test
def test_can_create(self):
data = {'name': 'test name', 'category': 1}
response = self.client.post(
self.url, data, format='json')
self.assertEqual(response.status_code, 201)
def test_detail_view(self):
sample_id = MyModel.objects.first().id
detail_url = self.url + '/' + str(sample_id)
response = self.client.get(detail_url, format='json')
self.assertEqual(response.status_code, 200)
More information:
http://www.django-rest-framework.org/api-guide/testing/
Homework!
●What Django projects do you have live?
○In development?
●Do they have public information?
●Collections of user data?
●Can’t think of a use? Users will!
Resources
Django Rest Framework Quickstart:
http://www.django-rest-framework.org/tutorial/quickstart/
Example Project:
https://github.com/flowerncsu/ecgc-2017
These Slides:
http://cakt.us/DjangoCon2017talk
Caktus Group:
@caktusgroup
https://www.caktusgroup.com/
My Twitter:
@charlottecodes

Contenu connexe

Tendances

Angular coding: from project management to web and mobile deploy
Angular coding: from project management to web and mobile deployAngular coding: from project management to web and mobile deploy
Angular coding: from project management to web and mobile deployCorley S.r.l.
 
Introducing swagger
Introducing swaggerIntroducing swagger
Introducing swaggerAmr Ali
 
Swagger in the API Lifecycle
Swagger in the API LifecycleSwagger in the API Lifecycle
Swagger in the API LifecycleOle Lensmar
 
Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!Andreas Dewes
 
AngularJS: Service, factory & provider
AngularJS: Service, factory & providerAngularJS: Service, factory & provider
AngularJS: Service, factory & providerCorley S.r.l.
 
Angular 2 : le réveil de la force
Angular 2 : le réveil de la forceAngular 2 : le réveil de la force
Angular 2 : le réveil de la forceNicolas PENNEC
 
Documentation-driven development for Python web APIs v2
Documentation-driven development for Python web APIs v2Documentation-driven development for Python web APIs v2
Documentation-driven development for Python web APIs v2José Haro Peralta
 
Writer APIs in Java faster with Swagger Inflector
Writer APIs in Java faster with Swagger InflectorWriter APIs in Java faster with Swagger Inflector
Writer APIs in Java faster with Swagger InflectorTony Tam
 
Design Driven API Development
Design Driven API DevelopmentDesign Driven API Development
Design Driven API DevelopmentSokichi Fujita
 
apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...
apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...
apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...apidays
 
Iterative Development with Swagger on the JDK
Iterative Development with Swagger on the JDKIterative Development with Swagger on the JDK
Iterative Development with Swagger on the JDKSwagger API
 
API Design first with Swagger
API Design first with SwaggerAPI Design first with Swagger
API Design first with SwaggerTony Tam
 
AzovDevMeetup 2016 | Angular 2: обзор | Александр Шевнин
AzovDevMeetup 2016 | Angular 2: обзор | Александр ШевнинAzovDevMeetup 2016 | Angular 2: обзор | Александр Шевнин
AzovDevMeetup 2016 | Angular 2: обзор | Александр ШевнинJSC “Arcadia Inc”
 
Introducing wsgi_lineprof / PyCon JP 2017 LT
Introducing wsgi_lineprof / PyCon JP 2017 LTIntroducing wsgi_lineprof / PyCon JP 2017 LT
Introducing wsgi_lineprof / PyCon JP 2017 LTYusuke Miyazaki
 
Angular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir KaufmanAngular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir KaufmanNir Kaufman
 
Swagger for-your-api
Swagger for-your-apiSwagger for-your-api
Swagger for-your-apiTony Tam
 
Swagger - make your API accessible
Swagger - make your API accessibleSwagger - make your API accessible
Swagger - make your API accessibleVictor Trakhtenberg
 
Corley cloud angular in cloud
Corley cloud   angular in cloudCorley cloud   angular in cloud
Corley cloud angular in cloudCorley S.r.l.
 

Tendances (20)

Swagger 2.0 and Model-driven APIs
Swagger 2.0 and Model-driven APIsSwagger 2.0 and Model-driven APIs
Swagger 2.0 and Model-driven APIs
 
Angular coding: from project management to web and mobile deploy
Angular coding: from project management to web and mobile deployAngular coding: from project management to web and mobile deploy
Angular coding: from project management to web and mobile deploy
 
Introducing swagger
Introducing swaggerIntroducing swagger
Introducing swagger
 
Swagger in the API Lifecycle
Swagger in the API LifecycleSwagger in the API Lifecycle
Swagger in the API Lifecycle
 
Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!
 
AngularJS: Service, factory & provider
AngularJS: Service, factory & providerAngularJS: Service, factory & provider
AngularJS: Service, factory & provider
 
Angular 2 : le réveil de la force
Angular 2 : le réveil de la forceAngular 2 : le réveil de la force
Angular 2 : le réveil de la force
 
Documentation-driven development for Python web APIs v2
Documentation-driven development for Python web APIs v2Documentation-driven development for Python web APIs v2
Documentation-driven development for Python web APIs v2
 
Writer APIs in Java faster with Swagger Inflector
Writer APIs in Java faster with Swagger InflectorWriter APIs in Java faster with Swagger Inflector
Writer APIs in Java faster with Swagger Inflector
 
Design Driven API Development
Design Driven API DevelopmentDesign Driven API Development
Design Driven API Development
 
apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...
apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...
apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...
 
Iterative Development with Swagger on the JDK
Iterative Development with Swagger on the JDKIterative Development with Swagger on the JDK
Iterative Development with Swagger on the JDK
 
React native
React nativeReact native
React native
 
API Design first with Swagger
API Design first with SwaggerAPI Design first with Swagger
API Design first with Swagger
 
AzovDevMeetup 2016 | Angular 2: обзор | Александр Шевнин
AzovDevMeetup 2016 | Angular 2: обзор | Александр ШевнинAzovDevMeetup 2016 | Angular 2: обзор | Александр Шевнин
AzovDevMeetup 2016 | Angular 2: обзор | Александр Шевнин
 
Introducing wsgi_lineprof / PyCon JP 2017 LT
Introducing wsgi_lineprof / PyCon JP 2017 LTIntroducing wsgi_lineprof / PyCon JP 2017 LT
Introducing wsgi_lineprof / PyCon JP 2017 LT
 
Angular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir KaufmanAngular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir Kaufman
 
Swagger for-your-api
Swagger for-your-apiSwagger for-your-api
Swagger for-your-api
 
Swagger - make your API accessible
Swagger - make your API accessibleSwagger - make your API accessible
Swagger - make your API accessible
 
Corley cloud angular in cloud
Corley cloud   angular in cloudCorley cloud   angular in cloud
Corley cloud angular in cloud
 

Similaire à Write an API for Almost Anything: The Amazing Power and Flexibility of Django Rest Framework

Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...Caktus Group
 
APIdays Paris 2014 - Workshop - Craft and Deploy Your API in a Few Clicks Wit...
APIdays Paris 2014 - Workshop - Craft and Deploy Your API in a Few Clicks Wit...APIdays Paris 2014 - Workshop - Craft and Deploy Your API in a Few Clicks Wit...
APIdays Paris 2014 - Workshop - Craft and Deploy Your API in a Few Clicks Wit...Restlet
 
Creating a custom API for a headless Drupal
Creating a custom API for a headless DrupalCreating a custom API for a headless Drupal
Creating a custom API for a headless DrupalExove
 
Introduction to Apigility
Introduction to ApigilityIntroduction to Apigility
Introduction to ApigilityEngineor
 
Apigility introduction v2 (glasgow php)
Apigility introduction v2 (glasgow php)Apigility introduction v2 (glasgow php)
Apigility introduction v2 (glasgow php)Engineor
 
API Management for GraphQL
API Management for GraphQLAPI Management for GraphQL
API Management for GraphQLWSO2
 
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...Fwdays
 
Build Android App using GCE & GAE
Build Android App using GCE & GAEBuild Android App using GCE & GAE
Build Android App using GCE & GAELove Sharma
 
Création d'application Ionic & Angular & Drupal 8
Création d'application Ionic & Angular & Drupal 8Création d'application Ionic & Angular & Drupal 8
Création d'application Ionic & Angular & Drupal 8wsmarouan
 
OpenAPI development with Python
OpenAPI development with PythonOpenAPI development with Python
OpenAPI development with PythonTakuro Wada
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIVisual Engineering
 
How to Create a Service in Choreo
How to Create a Service in ChoreoHow to Create a Service in Choreo
How to Create a Service in ChoreoWSO2
 
Deploying GraphQL Services as Managed APIs
Deploying GraphQL Services as Managed APIsDeploying GraphQL Services as Managed APIs
Deploying GraphQL Services as Managed APIsWSO2
 
EuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears TrainingEuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears TrainingAlessandro Molina
 
202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUP202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUPRonald Hsu
 
Google api應用入門
Google api應用入門Google api應用入門
Google api應用入門Simon Su
 
Mumbai MuleSoft Meetup #15
Mumbai MuleSoft Meetup #15Mumbai MuleSoft Meetup #15
Mumbai MuleSoft Meetup #15Akshata Sawant
 
Introduction to Google Cloud Endpoints: Speed Up Your API Development
Introduction to Google Cloud Endpoints: Speed Up Your API DevelopmentIntroduction to Google Cloud Endpoints: Speed Up Your API Development
Introduction to Google Cloud Endpoints: Speed Up Your API DevelopmentColin Su
 
Api best practices
Api best practicesApi best practices
Api best practicesChet Nut
 

Similaire à Write an API for Almost Anything: The Amazing Power and Flexibility of Django Rest Framework (20)

Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
 
APIdays Paris 2014 - Workshop - Craft and Deploy Your API in a Few Clicks Wit...
APIdays Paris 2014 - Workshop - Craft and Deploy Your API in a Few Clicks Wit...APIdays Paris 2014 - Workshop - Craft and Deploy Your API in a Few Clicks Wit...
APIdays Paris 2014 - Workshop - Craft and Deploy Your API in a Few Clicks Wit...
 
Creating a custom API for a headless Drupal
Creating a custom API for a headless DrupalCreating a custom API for a headless Drupal
Creating a custom API for a headless Drupal
 
Introduction to Apigility
Introduction to ApigilityIntroduction to Apigility
Introduction to Apigility
 
Apigility introduction v2 (glasgow php)
Apigility introduction v2 (glasgow php)Apigility introduction v2 (glasgow php)
Apigility introduction v2 (glasgow php)
 
Crafting APIs
Crafting APIsCrafting APIs
Crafting APIs
 
API Management for GraphQL
API Management for GraphQLAPI Management for GraphQL
API Management for GraphQL
 
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
 
Build Android App using GCE & GAE
Build Android App using GCE & GAEBuild Android App using GCE & GAE
Build Android App using GCE & GAE
 
Création d'application Ionic & Angular & Drupal 8
Création d'application Ionic & Angular & Drupal 8Création d'application Ionic & Angular & Drupal 8
Création d'application Ionic & Angular & Drupal 8
 
OpenAPI development with Python
OpenAPI development with PythonOpenAPI development with Python
OpenAPI development with Python
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 
How to Create a Service in Choreo
How to Create a Service in ChoreoHow to Create a Service in Choreo
How to Create a Service in Choreo
 
Deploying GraphQL Services as Managed APIs
Deploying GraphQL Services as Managed APIsDeploying GraphQL Services as Managed APIs
Deploying GraphQL Services as Managed APIs
 
EuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears TrainingEuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears Training
 
202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUP202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUP
 
Google api應用入門
Google api應用入門Google api應用入門
Google api應用入門
 
Mumbai MuleSoft Meetup #15
Mumbai MuleSoft Meetup #15Mumbai MuleSoft Meetup #15
Mumbai MuleSoft Meetup #15
 
Introduction to Google Cloud Endpoints: Speed Up Your API Development
Introduction to Google Cloud Endpoints: Speed Up Your API DevelopmentIntroduction to Google Cloud Endpoints: Speed Up Your API Development
Introduction to Google Cloud Endpoints: Speed Up Your API Development
 
Api best practices
Api best practicesApi best practices
Api best practices
 

Dernier

VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 

Dernier (20)

VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 

Write an API for Almost Anything: The Amazing Power and Flexibility of Django Rest Framework

  • 1. Write an API for Almost Anything DjangoCon 2017 The Amazing Power and Flexibility of Django Rest Framework
  • 2. Who Am I? ●Web Developer at Caktus Group ●Organizer of PyLadies RDU ●Builder and User of APIs Note: Slides available at: http://cakt.us/DjangoCon2017talk
  • 3. What does “API” mean, anyway? ● “Application Programming Interface” ● Definition (techtarget.com): “An application program interface (API) is code that allows two software programs to communicate with each other.”
  • 4. Why Are APIs Useful? ●Flexibility ●Access (internally and externally) ●Future-proofing
  • 5. Example: Customized Output ●Massage therapist needed schedule information to be sharable without client information ●Scheduling software did not do this ○But did have an API!
  • 6. Example: Customized Output ●Small script can pull schedule information and post without client information to a shareable calendar ●API made it possible to create an otherwise nonexistent feature
  • 7. APIs for Non-Web Applications ●Easy and practical enough to be useful for other distributed applications ●Example: Game back-end ○https://github.com/flowerncsu/ecgc-2017
  • 8. Internal Separation ●Dynamic, highly interactive pages require JavaScript ●Use API to separate Django code from JavaScript code
  • 9. Internal Separation ●Cleaner code ●Easier to use JS frameworks ●Retrieve data and context with simple requests
  • 10. APIs Are Awesome, So How Do I Build One?
  • 11. Building an API ●Many ways, many packages ●Django Rest Framework ○Sits nicely on top of existing Django code ○Very thorough feature set
  • 12. Anatomy of Django Rest Framework API Router ViewSet Serializer Django Models/ Database serializers.py views.py urls.py
  • 13. Anatomy of Django Rest Framework API Serializer Django Models/ Database
  • 14. Building the Serializer from rest_framework import serializers from .models import MyModel class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ( 'id', 'name', 'category', )
  • 15. Anatomy of Django Rest Framework API ViewSet Serializer Django Models/ Database
  • 16. Building the ViewSet from rest_framework import viewsets from .models import MyModel from .serializers import MyModelSerializer class MyModelViewSet(viewsets.ModelViewSet): """ API endpoint that allows MyModel instances to be viewed or edited. """ queryset = MyModel.objects.all() serializer_class = MyModelSerializer
  • 17. Anatomy of Django Rest Framework API Router ViewSet Serializer Django Models/ Database
  • 18. Building URLs with the Router from django.conf.urls import url, include from rest_framework import routers from myapp import views as myapp_api router = routers.DefaultRouter() router.register(r'mymodel', myapp_api.MyModelViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
  • 19. Accessing the API HTTP Methods Operations ●C ●R ●U ●D
  • 20. Accessing the API HTTP Methods ● POST Operations ●Create ●R ●U ●D
  • 21. Accessing the API HTTP Methods ● POST ● GET Operations ●Create ●Read ●U ●D
  • 22. Accessing the API HTTP Methods ● POST ● GET ● PUT ● PATCH Operations ●Create ●Read ●Update ●D
  • 23. Accessing the API HTTP Methods ● POST ● GET ● PUT ● PATCH ● DELETE Operations ●Create ●Read ●Update ●Delete
  • 24. Accessing the API HTTP Methods ● POST ● GET ● PUT ● PATCH ● DELETE Operations ●Create ●Read ●Update ●Delete
  • 25. Accessing the API router.register(r'mymodel', myapp_api.MyModelViewSet) (GET) myapp.com/mymodel -> List of instances, fields based on serializer (POST) myapp.com/mymodel -> Create a new instance (GET) myapp.com/mymodel/instance_id -> Get details for instance with instance_id (DELETE) myapp.com/mymodel/instance_id -> Delete instance with instance_id More information: http://www.django-rest-framework.org/api-guide/viewsets/
  • 26. What If I Don’t Want Users Doing That? Several options to protect data: ●Authentication ●Read-only Viewsets ●Restricting specific actions
  • 27. Documentation ●Key to usability of the API ●Structure is predictable ○URL and HTTP method ○Operation performed at that URL/method ○Parameters expected ○Data format returned More information: http://www.django-rest-framework.org/topics/documenting-your-api/
  • 28. Automatic Documentation from rest_framework.documentation import include_docs_urls ... urlpatterns = [ ... url(r'^docs/', include_docs_urls(title='My API')) ] More information: http://www.django-rest-framework.org/topics/documenting-your-api/
  • 29. Tests ● API functionality can be tested simply ●Automated tests mean “set it and forget it” ●Test failures can highlight changes that should be reflected in documentation
  • 30. Sample Test from rest_framework.test import APITestCase class TestMyModelViewSet(APITestCase): def setUp(self): self.url = reverse('mymodel-list') self.instances = [MyModel() for i in range(3)] for item in self.instances: item.save() def test_list_view(self): response = self.client.get(self.url, format='json') self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 3) More information: http://www.django-rest-framework.org/api-guide/testing/
  • 31. Sample Test def test_can_create(self): data = {'name': 'test name', 'category': 1} response = self.client.post( self.url, data, format='json') self.assertEqual(response.status_code, 201) def test_detail_view(self): sample_id = MyModel.objects.first().id detail_url = self.url + '/' + str(sample_id) response = self.client.get(detail_url, format='json') self.assertEqual(response.status_code, 200) More information: http://www.django-rest-framework.org/api-guide/testing/
  • 32. Homework! ●What Django projects do you have live? ○In development? ●Do they have public information? ●Collections of user data? ●Can’t think of a use? Users will!
  • 33. Resources Django Rest Framework Quickstart: http://www.django-rest-framework.org/tutorial/quickstart/ Example Project: https://github.com/flowerncsu/ecgc-2017 These Slides: http://cakt.us/DjangoCon2017talk Caktus Group: @caktusgroup https://www.caktusgroup.com/ My Twitter: @charlottecodes