SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
Django REST Framework
Jenny Olsson
Load Impact
Framework for building REST applications
pip install djangorestframework
Django REST Framework (DRF)
● URL-routing
● Views/ViewSets
● Serializers
What do you get from DRF:
We’ll assume we’ve got:
● A Django Application
● A Snail Model
Let’s build a snail API!
Request:
GET www.api.snails.com/snails/1
Reply:
{'id': 1,
'name': 'Helix Aspersa',
'description': 'Common garden snail'}
Example
from django.conf.urls import url, patterns, include
from rest_framework import routers
router = routers.DefaultRouter(trailing_slash=False)
# /snails
router.register(r'snails', SnailViewSet, base_name='snail')
urlpatterns = (patterns(
'',
url('', include(router.urls)),
))
URL routing
A ViewSet is a set of Views (this is a useful abstraction)
This is where you:
● Handle the request
● Check permissions
● Authenticate
● Define allowed methods
ViewSet
from rest_framework import viewsets
from snail_app import models
from serializers import SnailSerializer
class SnailViewSet(viewsets.ModelViewSet):
queryset = models.Snail.objects.all()
serializer_class = SnailSerializer
permission_classes = (IsMember,)
/views/snails.py
This is where you:
● Validate input
● Format input data
● Format output data
Serializers
from rest_framework import serializers
from snail_app import models
class SnailSerializer(serializers.ModelSerializer):
class Meta:
model = models.Snail
fields = (
'id',
'name',
'description'
)
/serializers/snails.py
Request:
GET www.api.snails.com/snails/1
Reply:
{'id': 1,
'name': 'Helix Aspersa',
'description': 'Common garden snail'}
Example
● I want to show you some more hacky stuff, because reality
I’ll go through how to
● Create a non REST endpoint
● Add a custom field to a serializer (and remove field)
DRF Website has good tutorials
Standard REST endpoints are connected to resource:
POST /snails <-- create snail
GET /snails <--- list snails
GET /snails/1 <--- get snail
UPDATE /snails/1 <--- update snail
But what if we want:
POST /snails/1/befriend ← befriend snail
Non REST endpoints
class SnailViewSet(viewsets.ModelViewSet):
…
@detail_route(methods=['post'])
def befriend(self, request, pk=None):
# Somehow befriend snail
return Response({'msg': 'Yay got snail friend'})
Use @detail_route or @list_route
Since we use ViewSets the endpoint will be automatically routed.
We can now befriend snails by posting to:
/snails/1/befriend
Automatic routing FTW
Our SnailSerializer is based on our model Snail.
But what if we want to return something that’s not a model field?
Adding custom fields
class SnailSerializer(serializers.ModelSerializer):
extra_snail_fact = serializers.SerializerMethodField()
class Meta:
model = models.Snail
fields = ('id', 'name', 'description', 'extra_snail_fact')
def get_extra_snail_fact(self, obj):
return 'snails really can’t swim:('
SerializerMethodField
Request:
GET www.api.snails.com/snails/1
Reply:
{'id': 1,
'name': 'Helix Aspersa',
'description': 'Common garden snail',
'extra_snail_fact': 'snails really can’t swim:('}
Example
But what if we DON’T want to return all the fields from our model?
class Snail(models.model):
…
super_embarrasing_hacky_field = 2
Removing fields
class SnailSerializer(serializers.ModelSerializer):
class Meta:
model = models.Snail
fields = ('id', 'name', 'description') # Just don’t add it here
SerializerMethodField
Django REST Framework is really powerful for making APIs
out of Django applications.
For something more lightweight I would probably recommend
flask.
Conclusion
Thanks for listening!
Ping me later if you’ve got any questions!
That’s it

Contenu connexe

Tendances

Tendances (20)

REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & Development
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
 
API Basics
API BasicsAPI Basics
API Basics
 
Introduction to back-end
Introduction to back-endIntroduction to back-end
Introduction to back-end
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
 
Introduction to API
Introduction to APIIntroduction to API
Introduction to API
 
What is an API?
What is an API?What is an API?
What is an API?
 
API
APIAPI
API
 
API Testing for everyone.pptx
API Testing for everyone.pptxAPI Testing for everyone.pptx
API Testing for everyone.pptx
 
introduction about REST API
introduction about REST APIintroduction about REST API
introduction about REST API
 
Full Stack Web Development
Full Stack Web DevelopmentFull Stack Web Development
Full Stack Web Development
 
Python web frameworks
Python web frameworksPython web frameworks
Python web frameworks
 
What is API - Understanding API Simplified
What is API - Understanding API SimplifiedWhat is API - Understanding API Simplified
What is API - Understanding API Simplified
 
Understanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple StepsUnderstanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple Steps
 
Rest api and-crud-api
Rest api and-crud-apiRest api and-crud-api
Rest api and-crud-api
 
What is an API
What is an APIWhat is an API
What is an API
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
 

En vedette

Django Web Application Security
Django Web Application SecurityDjango Web Application Security
Django Web Application Security
levigross
 
Basic Django ORM
Basic Django ORMBasic Django ORM
Basic Django ORM
Ayun Park
 
Django deployment best practices
Django deployment best practicesDjango deployment best practices
Django deployment best practices
Erik LaBianca
 
Do more than one thing at the same time, the Python way
Do more than one thing at the same time, the Python wayDo more than one thing at the same time, the Python way
Do more than one thing at the same time, the Python way
Jaime Buelta
 

En vedette (20)

Django rest framework tips and tricks
Django rest framework   tips and tricksDjango rest framework   tips and tricks
Django rest framework tips and tricks
 
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 MinutesDjangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJS
 
Django Web Application Security
Django Web Application SecurityDjango Web Application Security
Django Web Application Security
 
Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Get Django, Get Hired - An opinionated guide to getting the best job, for the...Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Get Django, Get Hired - An opinionated guide to getting the best job, for the...
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Django orm-tips
Django orm-tipsDjango orm-tips
Django orm-tips
 
Django Uni-Form
Django Uni-FormDjango Uni-Form
Django Uni-Form
 
Basic Django ORM
Basic Django ORMBasic Django ORM
Basic Django ORM
 
Django ORM
Django ORMDjango ORM
Django ORM
 
Building an API with Django and Django REST Framework
Building an API with Django and Django REST FrameworkBuilding an API with Django and Django REST Framework
Building an API with Django and Django REST Framework
 
Advanced Django ORM techniques
Advanced Django ORM techniquesAdvanced Django ORM techniques
Advanced Django ORM techniques
 
Django deployment best practices
Django deployment best practicesDjango deployment best practices
Django deployment best practices
 
Ansible on AWS
Ansible on AWSAnsible on AWS
Ansible on AWS
 
Django rest framework in 20 minuten
Django rest framework in 20 minutenDjango rest framework in 20 minuten
Django rest framework in 20 minuten
 
Flask and Paramiko for Python VA
Flask and Paramiko for Python VAFlask and Paramiko for Python VA
Flask and Paramiko for Python VA
 
Do more than one thing at the same time, the Python way
Do more than one thing at the same time, the Python wayDo more than one thing at the same time, the Python way
Do more than one thing at the same time, the Python way
 
Towards Continuous Deployment with Django
Towards Continuous Deployment with DjangoTowards Continuous Deployment with Django
Towards Continuous Deployment with Django
 
Implementation of RSA Algorithm for Speech Data Encryption and Decryption
Implementation of RSA Algorithm for Speech Data Encryption and DecryptionImplementation of RSA Algorithm for Speech Data Encryption and Decryption
Implementation of RSA Algorithm for Speech Data Encryption and Decryption
 
Two scoops of Django - Security Best Practices
Two scoops of Django - Security Best PracticesTwo scoops of Django - Security Best Practices
Two scoops of Django - Security Best Practices
 

Similaire à Django REST Framework

Keeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro frameworkKeeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro framework
Jeremy Kendall
 
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkKeeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro Framework
Jeremy Kendall
 
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
崇之 清水
 
What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012
D
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
Nick Sieger
 

Similaire à Django REST Framework (20)

Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in Ruby
 
Keeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro frameworkKeeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro framework
 
Keeping It Small with Slim
Keeping It Small with SlimKeeping It Small with Slim
Keeping It Small with Slim
 
Sinatra for REST services
Sinatra for REST servicesSinatra for REST services
Sinatra for REST services
 
AngularJS Tips&Tricks
AngularJS Tips&TricksAngularJS Tips&Tricks
AngularJS Tips&Tricks
 
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkKeeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro Framework
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
 
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
 
Quality Use Of Plugin
Quality Use Of PluginQuality Use Of Plugin
Quality Use Of Plugin
 
Complex Sites with Silex
Complex Sites with SilexComplex Sites with Silex
Complex Sites with Silex
 
"Angular.js Concepts in Depth" by Aleksandar Simović
"Angular.js Concepts in Depth" by Aleksandar Simović"Angular.js Concepts in Depth" by Aleksandar Simović
"Angular.js Concepts in Depth" by Aleksandar Simović
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
 
"Inside The AngularJS Directive Compiler" by Tero Parviainen
"Inside The AngularJS Directive Compiler" by Tero Parviainen"Inside The AngularJS Directive Compiler" by Tero Parviainen
"Inside The AngularJS Directive Compiler" by Tero Parviainen
 
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
 
PHP And Web Services: Perfect Partners
PHP And Web Services: Perfect PartnersPHP And Web Services: Perfect Partners
PHP And Web Services: Perfect Partners
 
Rapid prototyping and easy testing with ember cli mirage
Rapid prototyping and easy testing with ember cli mirageRapid prototyping and easy testing with ember cli mirage
Rapid prototyping and easy testing with ember cli mirage
 
What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
How to build an AngularJS backend-ready app WITHOUT BACKEND
How to build an AngularJS backend-ready app WITHOUT BACKEND How to build an AngularJS backend-ready app WITHOUT BACKEND
How to build an AngularJS backend-ready app WITHOUT BACKEND
 

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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 Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
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...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

Django REST Framework