SlideShare una empresa de Scribd logo
1 de 34
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Flask restfulservices
Flask restfulservicesFlask restfulservices
Flask restfulservicesMarcos Lin
 
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 2Graham Dumpleton
 
Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Lar21
 
What happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingWhat happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingJace Ju
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flaskJim Yeh
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebBryan Helmig
 
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 PollockCaldera Labs
 
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
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Elena Kolevska
 

La actualidad más candente (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
 

Destacado

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 AngularJSHannes Hapke
 
Django rest framework tips and tricks
Django rest framework   tips and tricksDjango rest framework   tips and tricks
Django rest framework tips and tricksxordoquy
 
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 2015Nina Zakharenko
 
Memory Management In Python The Basics
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The BasicsNina Zakharenko
 
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 cultureNina Zakharenko
 
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...Marcel Chastain
 
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...Zhe Li
 
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 APISFernando Rocha
 
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 APIMarcos Pereira
 
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 DecryptionMd. Ariful Hoque
 
Building Automated REST APIs with Python
Building Automated REST APIs with PythonBuilding Automated REST APIs with Python
Building Automated REST APIs with PythonJeff Knupp
 
Introduction To Single Page Application
Introduction To Single Page ApplicationIntroduction To Single Page Application
Introduction To Single Page ApplicationKMS Technology
 
12 tips on Django Best Practices
12 tips on Django Best Practices12 tips on Django Best Practices
12 tips on Django Best PracticesDavid Arcos
 
AhtleteTrax: for Athletes and Artist
AhtleteTrax: for Athletes and ArtistAhtleteTrax: for Athletes and Artist
AhtleteTrax: for Athletes and ArtistAaron Outlen
 
Saguenay police department interview questions
Saguenay police department interview questionsSaguenay police department interview questions
Saguenay police department interview questionsselinasimpson69
 
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 domainshahram yazdani
 
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 ashesMartijn van der Zee
 

Destacado (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
 

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

Java Technology
Java TechnologyJava Technology
Java Technologyifnu bima
 
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 GAERon Reiter
 
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 AssuredBas Dijkstra
 
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 ClarksonJoshua Long
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with DjangoSimon Willison
 
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 javascriptEldar Djafarov
 
Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009hugowetterberg
 
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 30fiyuer
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And DrupalPeter Arato
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfArthyR3
 
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 flaskJeetendra singh
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsDesigning CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsNeil Crookes
 
Creating Custom Drupal Modules
Creating Custom Drupal ModulesCreating Custom Drupal Modules
Creating Custom Drupal Modulestanoshimi
 
Http programming in play
Http programming in playHttp programming in play
Http programming in playKnoldus Inc.
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
nguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicenguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicehazzaz
 

Similar a 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
 

Último

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 educationjfdjdjcjdnsjd
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
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
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 

Último (20)

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
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
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
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

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/