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

Django Rest Framework - tips & trick
Django Rest Framework - tips & trick Django Rest Framework - tips & trick
Django Rest Framework - tips & trick Luca Zacchetti
 
Combining Django REST framework & Elasticsearch
Combining Django REST framework & ElasticsearchCombining Django REST framework & Elasticsearch
Combining Django REST framework & ElasticsearchYaroslav Muravskyi
 
Apache Sling as an OSGi-powered REST middleware
Apache Sling as an OSGi-powered REST middlewareApache Sling as an OSGi-powered REST middleware
Apache Sling as an OSGi-powered REST middlewareRobert Munteanu
 
Effective Web Application Development with Apache Sling
Effective Web Application Development with Apache SlingEffective Web Application Development with Apache Sling
Effective Web Application Development with Apache SlingRobert Munteanu
 
Mastering Grails 3 Plugins - Greach 2016
Mastering Grails 3 Plugins - Greach 2016Mastering Grails 3 Plugins - Greach 2016
Mastering Grails 3 Plugins - Greach 2016Alvaro Sanchez-Mariscal
 
RESTFul development with Apache sling
RESTFul development with Apache slingRESTFul development with Apache sling
RESTFul development with Apache slingSergii Fesenko
 
Capybara with Rspec
Capybara with RspecCapybara with Rspec
Capybara with RspecOmnia Helmi
 
Python tools for testing web services over HTTP
Python tools for testing web services over HTTPPython tools for testing web services over HTTP
Python tools for testing web services over HTTPMykhailo Kolesnyk
 
Building domain-specific testing tools : lessons learned from the Apache Slin...
Building domain-specific testing tools : lessons learned from the Apache Slin...Building domain-specific testing tools : lessons learned from the Apache Slin...
Building domain-specific testing tools : lessons learned from the Apache Slin...Robert Munteanu
 
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesomeEuroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesomeMetosin Oy
 
CIRCUIT 2015 - 10 Things Apache Sling Can Do
CIRCUIT 2015 - 10 Things Apache Sling Can DoCIRCUIT 2015 - 10 Things Apache Sling Can Do
CIRCUIT 2015 - 10 Things Apache Sling Can DoICF CIRCUIT
 
Test automation with Cucumber-JVM
Test automation with Cucumber-JVMTest automation with Cucumber-JVM
Test automation with Cucumber-JVMAlan Parkinson
 
Apigility – Lightning Fast API Development - OSSCamp 2014
Apigility – Lightning Fast API Development - OSSCamp 2014 Apigility – Lightning Fast API Development - OSSCamp 2014
Apigility – Lightning Fast API Development - OSSCamp 2014 OSSCube
 
Maarten Balliauw "Indexing and searching NuGet.org with Azure Functions and S...
Maarten Balliauw "Indexing and searching NuGet.org with Azure Functions and S...Maarten Balliauw "Indexing and searching NuGet.org with Azure Functions and S...
Maarten Balliauw "Indexing and searching NuGet.org with Azure Functions and S...Fwdays
 
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...Maarten Balliauw
 
Building Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET CoreBuilding Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET CoreStormpath
 
Intro to Web Development Using Python and Django
Intro to Web Development Using Python and DjangoIntro to Web Development Using Python and Django
Intro to Web Development Using Python and DjangoChariza Pladin
 
Unleash the power of HTTP with ASP.NET Web API
Unleash the power of HTTP with ASP.NET Web APIUnleash the power of HTTP with ASP.NET Web API
Unleash the power of HTTP with ASP.NET Web APIFilip W
 
Ci of js and apex using jasmine, phantom js and drone io df14
Ci of js and apex using jasmine, phantom js and drone io   df14Ci of js and apex using jasmine, phantom js and drone io   df14
Ci of js and apex using jasmine, phantom js and drone io df14Kevin Poorman
 
Making Watir and Cucumber an efficient tool for Web UI Automation
Making Watir and Cucumber an efficient tool for Web UI AutomationMaking Watir and Cucumber an efficient tool for Web UI Automation
Making Watir and Cucumber an efficient tool for Web UI AutomationRuslan Strazhnyk
 

Tendances (20)

Django Rest Framework - tips & trick
Django Rest Framework - tips & trick Django Rest Framework - tips & trick
Django Rest Framework - tips & trick
 
Combining Django REST framework & Elasticsearch
Combining Django REST framework & ElasticsearchCombining Django REST framework & Elasticsearch
Combining Django REST framework & Elasticsearch
 
Apache Sling as an OSGi-powered REST middleware
Apache Sling as an OSGi-powered REST middlewareApache Sling as an OSGi-powered REST middleware
Apache Sling as an OSGi-powered REST middleware
 
Effective Web Application Development with Apache Sling
Effective Web Application Development with Apache SlingEffective Web Application Development with Apache Sling
Effective Web Application Development with Apache Sling
 
Mastering Grails 3 Plugins - Greach 2016
Mastering Grails 3 Plugins - Greach 2016Mastering Grails 3 Plugins - Greach 2016
Mastering Grails 3 Plugins - Greach 2016
 
RESTFul development with Apache sling
RESTFul development with Apache slingRESTFul development with Apache sling
RESTFul development with Apache sling
 
Capybara with Rspec
Capybara with RspecCapybara with Rspec
Capybara with Rspec
 
Python tools for testing web services over HTTP
Python tools for testing web services over HTTPPython tools for testing web services over HTTP
Python tools for testing web services over HTTP
 
Building domain-specific testing tools : lessons learned from the Apache Slin...
Building domain-specific testing tools : lessons learned from the Apache Slin...Building domain-specific testing tools : lessons learned from the Apache Slin...
Building domain-specific testing tools : lessons learned from the Apache Slin...
 
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesomeEuroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
 
CIRCUIT 2015 - 10 Things Apache Sling Can Do
CIRCUIT 2015 - 10 Things Apache Sling Can DoCIRCUIT 2015 - 10 Things Apache Sling Can Do
CIRCUIT 2015 - 10 Things Apache Sling Can Do
 
Test automation with Cucumber-JVM
Test automation with Cucumber-JVMTest automation with Cucumber-JVM
Test automation with Cucumber-JVM
 
Apigility – Lightning Fast API Development - OSSCamp 2014
Apigility – Lightning Fast API Development - OSSCamp 2014 Apigility – Lightning Fast API Development - OSSCamp 2014
Apigility – Lightning Fast API Development - OSSCamp 2014
 
Maarten Balliauw "Indexing and searching NuGet.org with Azure Functions and S...
Maarten Balliauw "Indexing and searching NuGet.org with Azure Functions and S...Maarten Balliauw "Indexing and searching NuGet.org with Azure Functions and S...
Maarten Balliauw "Indexing and searching NuGet.org with Azure Functions and S...
 
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
Indexing and searching NuGet.org with Azure Functions and Search - .NET fwday...
 
Building Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET CoreBuilding Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET Core
 
Intro to Web Development Using Python and Django
Intro to Web Development Using Python and DjangoIntro to Web Development Using Python and Django
Intro to Web Development Using Python and Django
 
Unleash the power of HTTP with ASP.NET Web API
Unleash the power of HTTP with ASP.NET Web APIUnleash the power of HTTP with ASP.NET Web API
Unleash the power of HTTP with ASP.NET Web API
 
Ci of js and apex using jasmine, phantom js and drone io df14
Ci of js and apex using jasmine, phantom js and drone io   df14Ci of js and apex using jasmine, phantom js and drone io   df14
Ci of js and apex using jasmine, phantom js and drone io df14
 
Making Watir and Cucumber an efficient tool for Web UI Automation
Making Watir and Cucumber an efficient tool for Web UI AutomationMaking Watir and Cucumber an efficient tool for Web UI Automation
Making Watir and Cucumber an efficient tool for Web UI Automation
 

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
 
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
 
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
 
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
 
Build Android App using GCE & GAE
Build Android App using GCE & GAEBuild Android App using GCE & GAE
Build Android App using GCE & GAELove Sharma
 
Google App Engine Overview - BarCamp Phnom Penh 2011
Google App Engine Overview - BarCamp Phnom Penh 2011Google App Engine Overview - BarCamp Phnom Penh 2011
Google App Engine Overview - BarCamp Phnom Penh 2011traactivity
 
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
 
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
 
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
 
OpenAPI development with Python
OpenAPI development with PythonOpenAPI development with Python
OpenAPI development with PythonTakuro Wada
 
Building APIs the serverless way
Building APIs the serverless wayBuilding APIs the serverless way
Building APIs the serverless wayTessa Mero
 
Web App Prototypes with Google App Engine
Web App Prototypes with Google App EngineWeb App Prototypes with Google App Engine
Web App Prototypes with Google App EngineVlad Filippov
 
Introduction to App Engine Development
Introduction to App Engine DevelopmentIntroduction to App Engine Development
Introduction to App Engine DevelopmentRon Reiter
 
EuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears TrainingEuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears TrainingAlessandro Molina
 
Having fun with code igniter
Having fun with code igniterHaving fun with code igniter
Having fun with code igniterAhmad Arif
 
Deploying GraphQL Services as Managed APIs
Deploying GraphQL Services as Managed APIsDeploying GraphQL Services as Managed APIs
Deploying GraphQL Services as Managed APIsWSO2
 

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...
 
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
 
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...
 
Crafting APIs
Crafting APIsCrafting APIs
Crafting APIs
 
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)
 
API Management for GraphQL
API Management for GraphQLAPI Management for GraphQL
API Management for GraphQL
 
Build Android App using GCE & GAE
Build Android App using GCE & GAEBuild Android App using GCE & GAE
Build Android App using GCE & GAE
 
Google App Engine Overview - BarCamp Phnom Penh 2011
Google App Engine Overview - BarCamp Phnom Penh 2011Google App Engine Overview - BarCamp Phnom Penh 2011
Google App Engine Overview - BarCamp Phnom Penh 2011
 
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...
 
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
 
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
 
OpenAPI development with Python
OpenAPI development with PythonOpenAPI development with Python
OpenAPI development with Python
 
Building APIs the serverless way
Building APIs the serverless wayBuilding APIs the serverless way
Building APIs the serverless way
 
Web App Prototypes with Google App Engine
Web App Prototypes with Google App EngineWeb App Prototypes with Google App Engine
Web App Prototypes with Google App Engine
 
Introduction to App Engine Development
Introduction to App Engine DevelopmentIntroduction to App Engine Development
Introduction to App Engine Development
 
Api design part 1
Api design part 1Api design part 1
Api design part 1
 
EuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears TrainingEuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears Training
 
Having fun with code igniter
Having fun with code igniterHaving fun with code igniter
Having fun with code igniter
 
Deploying GraphQL Services as Managed APIs
Deploying GraphQL Services as Managed APIsDeploying GraphQL Services as Managed APIs
Deploying GraphQL Services as Managed APIs
 

Dernier

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 

Dernier (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

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