SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
APIS
with Django Rest
Framework
So easy, you can learn it in 25 minutes.
(No, seriously)
REST
Describes an architecture
For the purpose of web apis:
- stateless
- support common HTTP methods
- return internet media type (JSON or XML…)
HTTP Verbs
POST, GET, (PUT, PATCH), DELETE
Like CRUD… sort of.
What do REST endpoints look like?
/api/users/
- GET will return a collection of all users
/api/users/<id>
- GET will return a single user
Common HTTP Response Codes
200 - OK
201 - Created
401 - Not Authorized
404 - Not Found
500 - Server Error
Idempotency
Is a hard to pronounce word.
The operation will produce the same result,
no matter how many times it is repeated.
PUT, DELETE - Idempotent.
GET - Safe method. Produces no side effects.
Where DRF Comes in
It makes REST API creation easy!
Serializers
A Model
class Tweet(models.Model):
user = models.ForeignKey(User)
text = models.CharField(max_length=140)
timestamp = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-timestamp']
And a ModelSerializer
class TweetSerializer(serializers.ModelSerializer):
user = serializers.Field(source='user')
class Meta:
model = Tweet
fields = ('text', 'user', 'timestamp')
The Result
[
{
"text": "Bob is the coolest name EVAR",
"user": "bob",
"timestamp": "2014-08-29T18:51:19Z"
}
]
Validation
Field Validation
def validate_text(self, attrs, source):
value = attrs[source]
if len(value) < 5:
raise serializers.ValidationError(
"Text is too short!")
return attrs
Permissions
Permissions
IsAuthenticated - Only allow authenticated Users
IsAdminUser - user.is_staff is True
class IsAuthorOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.user == request.user
Views
ModelViewSets
class TweetViewSet(viewsets.ModelViewSet):
queryset = Tweet.objects.all()
serializer_class = TweetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsAuthorOrReadOnly,)
def pre_save(self, obj):
obj.user = self.request.user
Generic Views
APIView is base class. Takes care of routing.
Mixins provide common operations, and
generic Views provide common
combinations of mixins.
ex: ListCreateAPIView, UpdateAPIView
Requests
Requests
The DRF Request provides many methods we
are used to seeing.
request.DATA is similar to request.POST
It handles data types we specified, and is
available on all requests.
Responses
Responses
DRF Responses are unrendered.
Return DATA, and status code.
Behind the scenes:
serializer = TweetSerializer(tweets, many=True)
return Response(serializer.data)
Routing
ViewSet Routing
router = DefaultRouter()
router.register(r'tweets', views.TweetViewSet)
router.register(r'users', views.UserViewSet)
urlpatterns = patterns('',
url(r'^api/', include(router.urls))
)
Browsable API
Unit
Testing
Does our validation work?
def test_create_invalid_tweet(self):
self.client = APIClient()
self.client.login(username='bob', password='bob')
url = reverse('tweet-list')
data = {'text': "x" * 4}
response = self.client.post(url, data, format='json')
error_msg = response.data['text'][0]
self.assertEquals(response.status_code, 400)
self.assertEquals(error_msg, 'Text is too short!')
When to use it?
New projects.
- You don’t have to code for the framework,
but it’s easier to integrate.
Clean models.
When to be cautious (IMHO)
Complex models, tons of interdependent
validation logic, dealing with saving non-
model fields on a model
Legacy Django… It’s out there.
Doesn’t mean you shouldn’t go for it it, but
prepare for hurdles.
Next Steps
pip install djangorestframework
Also, the documentation rocks.
http://www.django-rest-framework.org/
Bye Everybody!
@nnja

Weitere ähnliche Inhalte

Was ist angesagt?

PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2
Graham Dumpleton
 
Powerful and flexible templates with Twig
Powerful and flexible templates with Twig Powerful and flexible templates with Twig
Powerful and flexible templates with Twig
Michael Peacock
 

Was ist angesagt? (20)

Flask restfulservices
Flask restfulservicesFlask restfulservices
Flask restfulservices
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2
 
Presentation
PresentationPresentation
Presentation
 
Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18
 
Rest in flask
Rest in flaskRest in flask
Rest in flask
 
What happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingWhat happens in laravel 4 bootstraping
What happens in laravel 4 bootstraping
 
Jsp
JspJsp
Jsp
 
Celery
CeleryCelery
Celery
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
 
Go database/sql
Go database/sqlGo database/sql
Go database/sql
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWeb
 
Django
DjangoDjango
Django
 
Extending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh PollockExtending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh Pollock
 
REST API Laravel
REST API LaravelREST API Laravel
REST API Laravel
 
Powerful and flexible templates with Twig
Powerful and flexible templates with Twig Powerful and flexible templates with Twig
Powerful and flexible templates with Twig
 
Introduction to Celery
Introduction to CeleryIntroduction to Celery
Introduction to Celery
 
CodeIgniter 3.0
CodeIgniter 3.0CodeIgniter 3.0
CodeIgniter 3.0
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Ant
AntAnt
Ant
 

Andere mochten auch

Introduction To Single Page Application
Introduction To Single Page ApplicationIntroduction To Single Page Application
Introduction To Single Page Application
KMS Technology
 
Saguenay police department interview questions
Saguenay police department interview questionsSaguenay police department interview questions
Saguenay police department interview questions
selinasimpson69
 

Andere mochten auch (20)

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 rest framework tips and tricks
Django rest framework   tips and tricksDjango rest framework   tips and tricks
Django rest framework tips and tricks
 
Nina Zakharenko - Introduction to Git - Start SLC 2015
Nina Zakharenko - Introduction to Git - Start SLC 2015Nina Zakharenko - Introduction to Git - Start SLC 2015
Nina Zakharenko - Introduction to Git - Start SLC 2015
 
Memory Management In Python The Basics
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The Basics
 
How to successfully grow a code review culture
How to successfully grow a code review cultureHow to successfully grow a code review culture
How to successfully grow a code review culture
 
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 Uni-Form
Django Uni-FormDjango Uni-Form
Django Uni-Form
 
Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...
 
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APISDJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
 
Django Rest Framework - Building a Web API
Django Rest Framework - Building a Web APIDjango Rest Framework - Building a Web API
Django Rest Framework - Building a Web API
 
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
 
Building Automated REST APIs with Python
Building Automated REST APIs with PythonBuilding Automated REST APIs with Python
Building Automated REST APIs with Python
 
Introduction To Single Page Application
Introduction To Single Page ApplicationIntroduction To Single Page Application
Introduction To Single Page Application
 
12 tips on Django Best Practices
12 tips on Django Best Practices12 tips on Django Best Practices
12 tips on Django Best Practices
 
AhtleteTrax: for Athletes and Artist
AhtleteTrax: for Athletes and ArtistAhtleteTrax: for Athletes and Artist
AhtleteTrax: for Athletes and Artist
 
Saguenay police department interview questions
Saguenay police department interview questionsSaguenay police department interview questions
Saguenay police department interview questions
 
A 1-6-learning objectives -cognitive domain
A 1-6-learning objectives -cognitive domainA 1-6-learning objectives -cognitive domain
A 1-6-learning objectives -cognitive domain
 
Think with Google 12/2012: Out of the ashes
Think with Google 12/2012: Out of the ashesThink with Google 12/2012: Out of the ashes
Think with Google 12/2012: Out of the ashes
 
It news
It newsIt news
It news
 

Ähnlich wie Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes

Java Technology
Java TechnologyJava Technology
Java Technology
ifnu bima
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
Eldar Djafarov
 
How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30
fiyuer
 
nguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicenguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-service
hazzaz
 

Ähnlich wie Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes (20)

Django Tastypie 101
Django Tastypie 101Django Tastypie 101
Django Tastypie 101
 
Java Technology
Java TechnologyJava Technology
Java Technology
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
Testing RESTful web services with REST Assured
Testing RESTful web services with REST AssuredTesting RESTful web services with REST Assured
Testing RESTful web services with REST Assured
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
 
Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009
 
How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
 
Servlet
Servlet Servlet
Servlet
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flask
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsDesigning CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIs
 
Creating Custom Drupal Modules
Creating Custom Drupal ModulesCreating Custom Drupal Modules
Creating Custom Drupal Modules
 
Http programming in play
Http programming in playHttp programming in play
Http programming in play
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Android networking-2
Android networking-2Android networking-2
Android networking-2
 
nguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicenguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-service
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Kürzlich hochgeladen (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes

  • 1. APIS with Django Rest Framework So easy, you can learn it in 25 minutes. (No, seriously)
  • 2. REST Describes an architecture For the purpose of web apis: - stateless - support common HTTP methods - return internet media type (JSON or XML…)
  • 3. HTTP Verbs POST, GET, (PUT, PATCH), DELETE Like CRUD… sort of.
  • 4. What do REST endpoints look like? /api/users/ - GET will return a collection of all users /api/users/<id> - GET will return a single user
  • 5. Common HTTP Response Codes 200 - OK 201 - Created 401 - Not Authorized 404 - Not Found 500 - Server Error
  • 6. Idempotency Is a hard to pronounce word. The operation will produce the same result, no matter how many times it is repeated. PUT, DELETE - Idempotent. GET - Safe method. Produces no side effects.
  • 7. Where DRF Comes in It makes REST API creation easy!
  • 9. A Model class Tweet(models.Model): user = models.ForeignKey(User) text = models.CharField(max_length=140) timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-timestamp']
  • 10. And a ModelSerializer class TweetSerializer(serializers.ModelSerializer): user = serializers.Field(source='user') class Meta: model = Tweet fields = ('text', 'user', 'timestamp')
  • 11. The Result [ { "text": "Bob is the coolest name EVAR", "user": "bob", "timestamp": "2014-08-29T18:51:19Z" } ]
  • 13. Field Validation def validate_text(self, attrs, source): value = attrs[source] if len(value) < 5: raise serializers.ValidationError( "Text is too short!") return attrs
  • 15. Permissions IsAuthenticated - Only allow authenticated Users IsAdminUser - user.is_staff is True class IsAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.user == request.user
  • 16. Views
  • 17. ModelViewSets class TweetViewSet(viewsets.ModelViewSet): queryset = Tweet.objects.all() serializer_class = TweetSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly,) def pre_save(self, obj): obj.user = self.request.user
  • 18. Generic Views APIView is base class. Takes care of routing. Mixins provide common operations, and generic Views provide common combinations of mixins. ex: ListCreateAPIView, UpdateAPIView
  • 20. Requests The DRF Request provides many methods we are used to seeing. request.DATA is similar to request.POST It handles data types we specified, and is available on all requests.
  • 22. Responses DRF Responses are unrendered. Return DATA, and status code. Behind the scenes: serializer = TweetSerializer(tweets, many=True) return Response(serializer.data)
  • 24. ViewSet Routing router = DefaultRouter() router.register(r'tweets', views.TweetViewSet) router.register(r'users', views.UserViewSet) urlpatterns = patterns('', url(r'^api/', include(router.urls)) )
  • 26.
  • 27.
  • 29. Does our validation work? def test_create_invalid_tweet(self): self.client = APIClient() self.client.login(username='bob', password='bob') url = reverse('tweet-list') data = {'text': "x" * 4} response = self.client.post(url, data, format='json') error_msg = response.data['text'][0] self.assertEquals(response.status_code, 400) self.assertEquals(error_msg, 'Text is too short!')
  • 30. When to use it? New projects. - You don’t have to code for the framework, but it’s easier to integrate. Clean models.
  • 31. When to be cautious (IMHO) Complex models, tons of interdependent validation logic, dealing with saving non- model fields on a model Legacy Django… It’s out there.
  • 32. Doesn’t mean you shouldn’t go for it it, but prepare for hurdles.
  • 33. Next Steps pip install djangorestframework Also, the documentation rocks. http://www.django-rest-framework.org/