SlideShare a Scribd company logo
1 of 50
RESTful APIs in Django: 
Library Face-Off! 
TastyPie vs Django REST Framework
Scope of Discussion 
● Introduction to REST 
● Review of Django’s Flow 
● Demo Structure Overview 
● Demo of TastyPie 
● Demo of Django Rest Framework 
● Demo of SQLAlchemy in both Frameworks 
● Conclusion
Introduction to REST 
● REST - Representational State Transfer 
● REST is a philosophy, not a communication protocol. 
o An architectural style for distributed systems just 
like the web 
o REST is not tied to the web, but it's almost always 
implemented as such, and was inspired by HTTP 
o Majority of RESTful APIs use HTTP serving JSON or XML.
Examples of REST Systems 
● Google Glass API 
● Twitter API 
● Amazon Web Services 
● Atom (RESTful alternative to RSS) 
● Tesla Model S 
o Uses RESTful calls to communicate between mobile 
devices and car: http://docs.timdorr.apiary.io/
REST
REST Characteristics 
● The term was introduced by Roy Fielding in 2000 for 
his in his doctoral dissertation at UC Irvine 
● 6 Constraints proposed by Roy Fielding 
o Client-Server 
o Stateless Server 
o Cache 
o Uniform Interface 
o Layered System
REST Characteristics 
● Client-Server Model: Pull Based (not event driven) system 
o Client - Sends requests to a server and awaits a response 
from the server. 
o Server - Provides a service to multiple clients. Receives 
requests and provides a response for the information that 
the client requested.
REST Characteristics 
● Stateless Server 
o Each request to the server must contain all of the 
information necessary for the server to understand the 
request. 
o Server cannot take advantage of any server-side stored 
context. 
● Ex: Server cannot know user’s profile before the request is 
made.
REST Characteristics 
● Cacheable Responses 
o Responses from the server have to be capable of being 
cached by the client (though this doesn’t need to be used). 
● Ex: Client stores locally the employee’s id for each 
consequent request after the initial request to login was 
successful.
REST Characteristics 
● Uniform Interface 
o Resource Identifier - URL / URI 
 http://twitter.com/#!/jack/status/20 
o Resource Representation and Manipulation 
 Whatever comes back that represents the resource identified by 
the URL. We can manipulate the resource directly from the URL. 
o Self-Descriptive Messages 
 Self-descriptive messages contain metadata to describe the 
meaning of the message. The methods used to invoke the message 
must be standard and agreeable between the first three 
constraints - client-server, stateless server, and cache.
REST Characteristics 
● Uniform Interface 
o HATEOAS - Hypermedia as 
the engine of application 
state 
 User requests resource 
 Resource has 
transitions (or 
hyperlinks) to go to a 
new state (new 
resources)
REST Characteristics 
● Layered System 
o Should be able to 
accommodate extra 
layers like proxy 
servers, firewalls, 
gateways, caching 
system 
o (this is why HTTP is 
most often used)
REST Characteristics 
● Code-on-Demand 
o The optional code-on-demand 
constraint 
allows clients to request 
and execute code from 
servers. This, in turn, 
allows the server to 
deploy new features to 
clients.
More Information 
● API Design: Ruminating Over REST 
o https://blog.apigee.com/detail/api_design_ruminat 
ing_over_rest 
● A Beginner's Guide to HTTP and REST 
o http://code.tutsplus.com/tutorials/a-beginners-guide- 
to-http-and-rest--net-16340 
● HATEOAS 
o https://www.youtube.com/watch?v=6UXc71O7htc
HTTP 
● Hypertext Transfer Protocol 
o Roy Fielding used REST to implement HTTP 1.1 
o The protocol that is used to manipulate remote 
resources. 
o We can use HTTP Verbs to manipulate these 
resources.
CRUD (Create, Read, Update, Delete) 
Operation HTTP Verb 
Get an element by it’s ID GET 
Get a list of elements GET 
Insert a new element POST or PUT (usually POST) 
Update an existing element PUT 
Delete an element DELETE 
Basic Operations for Manipulating Data over HTTP
To most people, REST just means... 
● Expose directory-structure-like URLS 
● Use HTTP methods correctly / consistently 
● Transfer XML or JSON 
● Be stateless 
o The same call should always yield the same result 
regardless of server state / previous calls made
What are the Benefits? 
● Separation of frontend and backend logic 
o easy to change your frontend client without touching your API 
o can add multiple clients (web, mobile, desktop app, batch 
process, etc) with no logic changes 
o gives a clear API layer to document. 
● Only one protocol for accessing backend logic: changes 
only need to be made in one place. 
● Predictable since it is stateless
What are the Benefits? 
● You can make good use of HTTP caching and proxy 
servers / load balancers to help you handle high load. 
● It helps you organize very complex applications into 
simple resources. 
● It makes it easy for new clients to use your application, 
even if you haven’t designed it specifically for them.
Why is this example #1 not RESTful? 
Bret lives in Oregon. His 
address is part of his user 
profile – not sent with every 
API call 
When he performs a GET call 
on the URL 
/cars/used/9000/12000/ 
To search for used cars in his 
price range, he gets back only 
results for within 50 miles of 
his address.
Example 1: Find Cars for User 
URL: http://foo.bar.com/cars/used/ 
Request: 
Method: GET 
Request Payload: 
{ 
"username" : "bobschmoe", 
"query" : "nearby" 
} 
Response: 
{ 
"results” : [{ 
"car_id" : "ABC001”, 
"make” : "Honda”, 
"model” : "Accord” }, { 
"car_id” : "ABC001”, 
"make” : "Honda”, 
"model” : "Accord” 
}], 
"zip": "11040" 
}
Example 1: Find Cars for User 
It is NOT RESTful since it is not stateless. 
● The server some how knew the user’s zip 
code. The client didn’t provide this 
information to the server.
Example 2: Add Vehicle to Company Profile 
URL: http://profile.mycompany.com/api/ 
Request: 
Method: POST 
Request Payload: 
{ 
"resource" : "vehicle", 
"method" : "addVehicle", 
"year" : "2014", 
"make" : "Honda", 
"model" : "Accord", 
"trim" : "EX-L", 
} 
Response: 
{ 
"resource_id" : "ABC00234", 
}
Example 2: Add Vehicle to Company Profile 
It is NOT RESTful since the URI is not 
unique. 
● Unique resources are not tied to a unique 
URI. They all share one. 
● Due to all requests being routed through one 
URI (/api/), no results have the ability to be 
cachable.
Example #3: Modifying Patient Information 
URL: http://mymeds.com/patients?method=updateAddress&patient_id=3254 
Request: 
Method: POST 
Request Payload: 
{ 
"address" : "123 Main Street", 
"city" : "Lake Success", 
"state" : "NY", 
} 
Response: 
{ 
"success" : "true" 
}
Example #3: Modifying Patient Information 
This is NOT RESTful because the 
resource has state information. 
● The client is making this call in order to change the state of the _ 
data on the server. But the client is using the GET method instead 
of the PUT method. 
● REST specifies that A resource is uniquely tied to a single URI and 
that the correct method is used to create, read, update, or delete it.
Example #3: Modifying Patient Information 
This is NOT RESTful because the 
resource has state information. 
● Tunneling all calls through GET is the primary REST anti-pattern! 
The base URI here - /patients/ - is not uniquely tied to a resource. 
● /patient/address/32543/ used together with PUT would be better.
Django Request-Response Cycle 
B 
r 
o 
w 
s 
e 
r 
Django 
urlpatterns = patterns( 
'', 
# Examples: 
# url(r'^$', 'notematic3000.views.home', name='home'), 
url(r'^note/(?P<pk>d+)/update/(?P<params>.+)', 
views.UpdateNote.as_view(), name='update'), 
url(r'^note/(?P<pk>d+)/delete', 
views.DeleteNote.as_view(), name='delete'), 
url(r'^note/(?P<%s>d+)' % PK, 
views.DisplayNote.as_view(), name=DISPLAY), 
url(r'^new/(?P<params>.+)', 
views.CreateNote.as_view(), name='create'), 
url(r'^(all)?', views.AllNotes.as_view(), name=GETALL), 
) 
Selected view 
● Receives request object 
● Responsible for all 
processing of request 
● One view will process 
different methods 
● Performs database 
interactions using ORM 
● Creates response 
● Returns response 
object 
GET 
note/3 
G 
E 
T 
n 
o 
t 
e 
/ 
3 
Response - (e.g. JSON text)
Demo Structure Overview
Project Structure 
notematic3000 
|----------------------------------------------- notes 
|-- Makefile |----------------------------- api 
|-- manage.py |-- admin.py |-- __init__.py 
|-- notematic3000 |-- alchemy |-- rest 
|------------------------ urls | |-- __init__.py | |-- __init__.py 
|-- crossbrowser.py |-- default.py | `-- notemanager.py | |-- routers.py 
|-- db.sqlite3 |-- __init__.py |-- constants.py | |-- serializers.py 
|-- __init__.py |-- pie.py |-- __init__.py | |-- sqlalchemy_viewset.py 
|-- settings `-- rest.py |-- models.py | `-- viewsets.py 
| |-- base.py |-- tests.py `-- tastypie 
| |-- default.py |-- urls.py |-- api.py 
| |-- __init__.py `-- views.py |-- __init__.py 
| |-- pie.py `-- sqlalchemy_api.py 
| `-- rest.py 
`-- wsgi.py
Project Settings 
from base import * 
# MODIFY INSTALLED APPS 
INSTALLED_APPS = INSTALLED_APPS + ('rest_framework',) 
# MODIFY URLS 
ROOT_URLCONF = 'notematic3000.urls.rest' 
# DJANGO REST FRAMEWORK SETTINGS 
REST_FRAMEWORK = { 
'DEFAULT_RENDERER_CLASSES' : ( 
'rest_framework.renderers.BrowsableAPIRenderer', 
'rest_framework.renderers.JSONRenderer', 
'rest_framework.renderers.XMLRenderer', ) }
Project Structure 
notematic3000 
|----------------------------------------------- notes 
|-- Makefile |----------------------------- api 
|-- manage.py |-- admin.py |-- __init__.py 
|-- notematic3000 |-- alchemy |-- rest 
|------------------------ urls | |-- __init__.py | |-- __init__.py 
|-- crossbrowser.py |-- default.py | `-- notemanager.py | |-- routers.py 
|-- db.sqlite3 |-- __init__.py |-- constants.py | |-- serializers.py 
|-- __init__.py |-- pie.py |-- __init__.py | |-- sqlalchemy_viewset.py 
|-- settings `-- rest.py |-- models.py | `-- viewsets.py 
| |-- base.py |-- tests.py `-- tastypie 
| |-- default.py |-- urls.py |-- api.py 
| |-- __init__.py `-- views.py |-- __init__.py 
| |-- pie.py `-- sqlalchemy_api.py 
| `-- rest.py 
`-- wsgi.py
Introduction to DRF 
Django REST framework is a powerful and 
flexible toolkit that makes it easy to build Web 
APIs.
DRF - Routers 
● REST framework adds support for automatic URL 
routing to Django, and provides you with a simple, 
quick and consistent way of wiring your view logic to a 
set of URLs. 
● Types of Routers 
o SimpleRouter 
o DefaultRouter 
o CustomRouters
DRF - Parsers 
● REST framework includes a number of built in Parser 
classes, that allow you to accept requests with various 
media types. There is also support for defining your own 
custom parsers, which gives you the flexibility to design 
the media types that your API accepts. 
● Types of Parsers 
o Built-In: 
 JSONParser, YAMLParser, XMLParser, 
FormParser, MultiPartParser, FileUploadParser 
o You can build your own custom parser
DRF - ViewSets 
● Django REST framework allows you to combine the 
logic for a set of related views in a single class, called a 
ViewSet. In other frameworks you may also find 
conceptually similar implementations named something 
like 'Resources' or 'Controllers'. 
● Types of ViewSets: 
o Built-In: 
 GenericViewSet, ModelViewSet, 
ReadOnlyModelViewSet 
o You can build your own custom ViewSet
DRF - Renderers 
● REST framework includes a number of built 
in Renderer classes, that allow you to return 
responses with various media types.
DRF - Renderers 
● Built-in Renderers 
o JSONRenderer, UnicodeJSONRenderer, 
JSONPRenderer, YAMLRenderer, XMLRenderer, 
TemplateHTMLRenderer, 
StaticHTMLRenderer,HTMLFormRenderer, 
BrowsableAPIRenderer, MultiPartRenderer 
o Custom Renderers
Other Features 
● Authorization 
o BasicAuthorization, TokenAuthorization, 
SessionAuthorization, OAuthAuthorization, 
OAuth2Authorization, CustomAuthorization 
● Permissions 
● Throttling 
● Filtering 
● Pagination
DEMO TIME
Introduction to Tastypie 
● Tastypie is a framework providing boilerplate code to 
create RESTful APIs 
● Depends on Django - cannot stand alone 
● Basically involves creating ‘Resource’ oriented classes 
● Resources are intermediary between end-user and 
Django models 
● Provides out-of-box authentication, authorization, 
caching, throttling and serialization
Tastypie Request Flow 
HTTP Request 
Django URL Resolver check 
Lookup view for match 
Check for serialization errors 
call dispatch 
dispatch method call 
HTTP method in allowed list? 
Authenticate/Authorize 
Throttle check 
call actual method
Advanced Tastypie 
● Bundles - Abstraction to pass data between resources 
● Api - Collection of resources 
● Resource Fields - Representation of resource (just like 
Django Fields) 
● You can customize authentication, authorization, 
caching, throttling, validation, serialization 
● Learn more at http://django-tastypie.readthedocs.org/
DEMO TIME
Non-Django ORM sources 
● What if - we cannot use Django ORM and we 
need something more advanced? 
● Both frameworks have hooks to replace 
Django ORM 
● Tastypie - Extend and override ‘Resource’ 
methods 
● DRF - Extend and override ‘ViewSet’ 
methods
Conclusion (1) 
● REST is now the standard for open APIs 
● REST is best summed up as verbs + nouns in 
URLS 
● Django app is structured as urls + views + 
models + stuff to make it easier 
● Provides ORM 
● Lots of libraries which build off it
Conclusion (2) 
● DRF documentation is better and well-structured 
● DRF is modular, pluggable, easy to understand 
● DRF supports web-browsable APIs and oAuth2 
● DRF has better integration with Swagger 
● TastyPie is older, can do anything, but is less 
Django-style
The Verdict 
Description DRF TastyPie 
Git Commits 
Web-browsable APIs Yes No 
Throttling Yes Yes 
Caching Yes Yes 
Form Validation No Yes 
oAuth2 Yes No 
Documentation Well-structured, easy to find Good, but not good enough 
Ease of use APIs are Django-like, easier to 
understand and hence use 
APIs hard to understand and 
hence use 
Swagger Better integration Does integrate, but takes effort

More Related Content

Viewers also liked

Django Framework and Application Structure
Django Framework and Application StructureDjango Framework and Application Structure
Django Framework and Application StructureSEONGTAEK OH
 
시맨틱 웹과 링크드데이터
시맨틱 웹과 링크드데이터시맨틱 웹과 링크드데이터
시맨틱 웹과 링크드데이터Haklae Kim
 
Building a custom cms with django
Building a custom cms with djangoBuilding a custom cms with django
Building a custom cms with djangoYann Malet
 
Real time web_apps_pycon2012-v1
Real time web_apps_pycon2012-v1Real time web_apps_pycon2012-v1
Real time web_apps_pycon2012-v1Avinash Prasad
 
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
 
PyConMY 2016 Django Channels
PyConMY 2016 Django ChannelsPyConMY 2016 Django Channels
PyConMY 2016 Django ChannelsKok Hoor Chew
 
"Модифицируй это!" или "Больше магии Python с помощью изменения AST"
"Модифицируй это!" или "Больше магии Python с помощью изменения AST""Модифицируй это!" или "Больше магии Python с помощью изменения AST"
"Модифицируй это!" или "Больше магии Python с помощью изменения AST"PyNSK
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersRosario Renga
 
Django rest framework tips and tricks
Django rest framework   tips and tricksDjango rest framework   tips and tricks
Django rest framework tips and tricksxordoquy
 
Pycon Australia 2011 Keynote - Audrey Roy
Pycon Australia 2011 Keynote - Audrey RoyPycon Australia 2011 Keynote - Audrey Roy
Pycon Australia 2011 Keynote - Audrey RoyAudrey Roy
 
Separating REST Facts from Fallacies
Separating REST Facts from FallaciesSeparating REST Facts from Fallacies
Separating REST Facts from FallaciesAlan Dean
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkMarcel Chastain
 
Amazing Things: Third-Party Python Package Ecosystems
Amazing Things: Third-Party Python Package EcosystemsAmazing Things: Third-Party Python Package Ecosystems
Amazing Things: Third-Party Python Package EcosystemsAudrey Roy
 
Django Package Thunderdome by Audrey Roy & Daniel Greenfeld
Django Package Thunderdome by Audrey Roy & Daniel GreenfeldDjango Package Thunderdome by Audrey Roy & Daniel Greenfeld
Django Package Thunderdome by Audrey Roy & Daniel GreenfeldAudrey Roy
 
Kiwi PyCon 2011 - Audrey Roy Keynote Speech
Kiwi PyCon 2011 - Audrey Roy Keynote SpeechKiwi PyCon 2011 - Audrey Roy Keynote Speech
Kiwi PyCon 2011 - Audrey Roy Keynote SpeechAudrey Roy
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial之宇 趙
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Eric Palakovich Carr
 
The State of WebSockets in Django
The State of WebSockets in DjangoThe State of WebSockets in Django
The State of WebSockets in DjangoRami Sayar
 

Viewers also liked (20)

Django Framework and Application Structure
Django Framework and Application StructureDjango Framework and Application Structure
Django Framework and Application Structure
 
시맨틱 웹과 링크드데이터
시맨틱 웹과 링크드데이터시맨틱 웹과 링크드데이터
시맨틱 웹과 링크드데이터
 
Building a custom cms with django
Building a custom cms with djangoBuilding a custom cms with django
Building a custom cms with django
 
Real time web_apps_pycon2012-v1
Real time web_apps_pycon2012-v1Real time web_apps_pycon2012-v1
Real time web_apps_pycon2012-v1
 
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
 
PyConMY 2016 Django Channels
PyConMY 2016 Django ChannelsPyConMY 2016 Django Channels
PyConMY 2016 Django Channels
 
"Модифицируй это!" или "Больше магии Python с помощью изменения AST"
"Модифицируй это!" или "Больше магии Python с помощью изменения AST""Модифицируй это!" или "Больше магии Python с помощью изменения AST"
"Модифицируй это!" или "Больше магии Python с помощью изменения AST"
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python Developers
 
Django
DjangoDjango
Django
 
Django rest framework tips and tricks
Django rest framework   tips and tricksDjango rest framework   tips and tricks
Django rest framework tips and tricks
 
Pycon Australia 2011 Keynote - Audrey Roy
Pycon Australia 2011 Keynote - Audrey RoyPycon Australia 2011 Keynote - Audrey Roy
Pycon Australia 2011 Keynote - Audrey Roy
 
Separating REST Facts from Fallacies
Separating REST Facts from FallaciesSeparating REST Facts from Fallacies
Separating REST Facts from Fallacies
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
 
Amazing Things: Third-Party Python Package Ecosystems
Amazing Things: Third-Party Python Package EcosystemsAmazing Things: Third-Party Python Package Ecosystems
Amazing Things: Third-Party Python Package Ecosystems
 
Django Package Thunderdome by Audrey Roy & Daniel Greenfeld
Django Package Thunderdome by Audrey Roy & Daniel GreenfeldDjango Package Thunderdome by Audrey Roy & Daniel Greenfeld
Django Package Thunderdome by Audrey Roy & Daniel Greenfeld
 
Kiwi PyCon 2011 - Audrey Roy Keynote Speech
Kiwi PyCon 2011 - Audrey Roy Keynote SpeechKiwi PyCon 2011 - Audrey Roy Keynote Speech
Kiwi PyCon 2011 - Audrey Roy Keynote Speech
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
The State of WebSockets in Django
The State of WebSockets in DjangoThe State of WebSockets in Django
The State of WebSockets in Django
 
Django Celery
Django Celery Django Celery
Django Celery
 

Recently uploaded

Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 

Recently uploaded (20)

Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 

Django Rest Framework vs Django TastyPie

  • 1. RESTful APIs in Django: Library Face-Off! TastyPie vs Django REST Framework
  • 2. Scope of Discussion ● Introduction to REST ● Review of Django’s Flow ● Demo Structure Overview ● Demo of TastyPie ● Demo of Django Rest Framework ● Demo of SQLAlchemy in both Frameworks ● Conclusion
  • 3. Introduction to REST ● REST - Representational State Transfer ● REST is a philosophy, not a communication protocol. o An architectural style for distributed systems just like the web o REST is not tied to the web, but it's almost always implemented as such, and was inspired by HTTP o Majority of RESTful APIs use HTTP serving JSON or XML.
  • 4. Examples of REST Systems ● Google Glass API ● Twitter API ● Amazon Web Services ● Atom (RESTful alternative to RSS) ● Tesla Model S o Uses RESTful calls to communicate between mobile devices and car: http://docs.timdorr.apiary.io/
  • 6. REST Characteristics ● The term was introduced by Roy Fielding in 2000 for his in his doctoral dissertation at UC Irvine ● 6 Constraints proposed by Roy Fielding o Client-Server o Stateless Server o Cache o Uniform Interface o Layered System
  • 7. REST Characteristics ● Client-Server Model: Pull Based (not event driven) system o Client - Sends requests to a server and awaits a response from the server. o Server - Provides a service to multiple clients. Receives requests and provides a response for the information that the client requested.
  • 8. REST Characteristics ● Stateless Server o Each request to the server must contain all of the information necessary for the server to understand the request. o Server cannot take advantage of any server-side stored context. ● Ex: Server cannot know user’s profile before the request is made.
  • 9. REST Characteristics ● Cacheable Responses o Responses from the server have to be capable of being cached by the client (though this doesn’t need to be used). ● Ex: Client stores locally the employee’s id for each consequent request after the initial request to login was successful.
  • 10. REST Characteristics ● Uniform Interface o Resource Identifier - URL / URI  http://twitter.com/#!/jack/status/20 o Resource Representation and Manipulation  Whatever comes back that represents the resource identified by the URL. We can manipulate the resource directly from the URL. o Self-Descriptive Messages  Self-descriptive messages contain metadata to describe the meaning of the message. The methods used to invoke the message must be standard and agreeable between the first three constraints - client-server, stateless server, and cache.
  • 11. REST Characteristics ● Uniform Interface o HATEOAS - Hypermedia as the engine of application state  User requests resource  Resource has transitions (or hyperlinks) to go to a new state (new resources)
  • 12. REST Characteristics ● Layered System o Should be able to accommodate extra layers like proxy servers, firewalls, gateways, caching system o (this is why HTTP is most often used)
  • 13. REST Characteristics ● Code-on-Demand o The optional code-on-demand constraint allows clients to request and execute code from servers. This, in turn, allows the server to deploy new features to clients.
  • 14. More Information ● API Design: Ruminating Over REST o https://blog.apigee.com/detail/api_design_ruminat ing_over_rest ● A Beginner's Guide to HTTP and REST o http://code.tutsplus.com/tutorials/a-beginners-guide- to-http-and-rest--net-16340 ● HATEOAS o https://www.youtube.com/watch?v=6UXc71O7htc
  • 15. HTTP ● Hypertext Transfer Protocol o Roy Fielding used REST to implement HTTP 1.1 o The protocol that is used to manipulate remote resources. o We can use HTTP Verbs to manipulate these resources.
  • 16. CRUD (Create, Read, Update, Delete) Operation HTTP Verb Get an element by it’s ID GET Get a list of elements GET Insert a new element POST or PUT (usually POST) Update an existing element PUT Delete an element DELETE Basic Operations for Manipulating Data over HTTP
  • 17. To most people, REST just means... ● Expose directory-structure-like URLS ● Use HTTP methods correctly / consistently ● Transfer XML or JSON ● Be stateless o The same call should always yield the same result regardless of server state / previous calls made
  • 18. What are the Benefits? ● Separation of frontend and backend logic o easy to change your frontend client without touching your API o can add multiple clients (web, mobile, desktop app, batch process, etc) with no logic changes o gives a clear API layer to document. ● Only one protocol for accessing backend logic: changes only need to be made in one place. ● Predictable since it is stateless
  • 19. What are the Benefits? ● You can make good use of HTTP caching and proxy servers / load balancers to help you handle high load. ● It helps you organize very complex applications into simple resources. ● It makes it easy for new clients to use your application, even if you haven’t designed it specifically for them.
  • 20. Why is this example #1 not RESTful? Bret lives in Oregon. His address is part of his user profile – not sent with every API call When he performs a GET call on the URL /cars/used/9000/12000/ To search for used cars in his price range, he gets back only results for within 50 miles of his address.
  • 21. Example 1: Find Cars for User URL: http://foo.bar.com/cars/used/ Request: Method: GET Request Payload: { "username" : "bobschmoe", "query" : "nearby" } Response: { "results” : [{ "car_id" : "ABC001”, "make” : "Honda”, "model” : "Accord” }, { "car_id” : "ABC001”, "make” : "Honda”, "model” : "Accord” }], "zip": "11040" }
  • 22. Example 1: Find Cars for User It is NOT RESTful since it is not stateless. ● The server some how knew the user’s zip code. The client didn’t provide this information to the server.
  • 23. Example 2: Add Vehicle to Company Profile URL: http://profile.mycompany.com/api/ Request: Method: POST Request Payload: { "resource" : "vehicle", "method" : "addVehicle", "year" : "2014", "make" : "Honda", "model" : "Accord", "trim" : "EX-L", } Response: { "resource_id" : "ABC00234", }
  • 24. Example 2: Add Vehicle to Company Profile It is NOT RESTful since the URI is not unique. ● Unique resources are not tied to a unique URI. They all share one. ● Due to all requests being routed through one URI (/api/), no results have the ability to be cachable.
  • 25. Example #3: Modifying Patient Information URL: http://mymeds.com/patients?method=updateAddress&patient_id=3254 Request: Method: POST Request Payload: { "address" : "123 Main Street", "city" : "Lake Success", "state" : "NY", } Response: { "success" : "true" }
  • 26. Example #3: Modifying Patient Information This is NOT RESTful because the resource has state information. ● The client is making this call in order to change the state of the _ data on the server. But the client is using the GET method instead of the PUT method. ● REST specifies that A resource is uniquely tied to a single URI and that the correct method is used to create, read, update, or delete it.
  • 27. Example #3: Modifying Patient Information This is NOT RESTful because the resource has state information. ● Tunneling all calls through GET is the primary REST anti-pattern! The base URI here - /patients/ - is not uniquely tied to a resource. ● /patient/address/32543/ used together with PUT would be better.
  • 28. Django Request-Response Cycle B r o w s e r Django urlpatterns = patterns( '', # Examples: # url(r'^$', 'notematic3000.views.home', name='home'), url(r'^note/(?P<pk>d+)/update/(?P<params>.+)', views.UpdateNote.as_view(), name='update'), url(r'^note/(?P<pk>d+)/delete', views.DeleteNote.as_view(), name='delete'), url(r'^note/(?P<%s>d+)' % PK, views.DisplayNote.as_view(), name=DISPLAY), url(r'^new/(?P<params>.+)', views.CreateNote.as_view(), name='create'), url(r'^(all)?', views.AllNotes.as_view(), name=GETALL), ) Selected view ● Receives request object ● Responsible for all processing of request ● One view will process different methods ● Performs database interactions using ORM ● Creates response ● Returns response object GET note/3 G E T n o t e / 3 Response - (e.g. JSON text)
  • 30. Project Structure notematic3000 |----------------------------------------------- notes |-- Makefile |----------------------------- api |-- manage.py |-- admin.py |-- __init__.py |-- notematic3000 |-- alchemy |-- rest |------------------------ urls | |-- __init__.py | |-- __init__.py |-- crossbrowser.py |-- default.py | `-- notemanager.py | |-- routers.py |-- db.sqlite3 |-- __init__.py |-- constants.py | |-- serializers.py |-- __init__.py |-- pie.py |-- __init__.py | |-- sqlalchemy_viewset.py |-- settings `-- rest.py |-- models.py | `-- viewsets.py | |-- base.py |-- tests.py `-- tastypie | |-- default.py |-- urls.py |-- api.py | |-- __init__.py `-- views.py |-- __init__.py | |-- pie.py `-- sqlalchemy_api.py | `-- rest.py `-- wsgi.py
  • 31. Project Settings from base import * # MODIFY INSTALLED APPS INSTALLED_APPS = INSTALLED_APPS + ('rest_framework',) # MODIFY URLS ROOT_URLCONF = 'notematic3000.urls.rest' # DJANGO REST FRAMEWORK SETTINGS REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES' : ( 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.XMLRenderer', ) }
  • 32. Project Structure notematic3000 |----------------------------------------------- notes |-- Makefile |----------------------------- api |-- manage.py |-- admin.py |-- __init__.py |-- notematic3000 |-- alchemy |-- rest |------------------------ urls | |-- __init__.py | |-- __init__.py |-- crossbrowser.py |-- default.py | `-- notemanager.py | |-- routers.py |-- db.sqlite3 |-- __init__.py |-- constants.py | |-- serializers.py |-- __init__.py |-- pie.py |-- __init__.py | |-- sqlalchemy_viewset.py |-- settings `-- rest.py |-- models.py | `-- viewsets.py | |-- base.py |-- tests.py `-- tastypie | |-- default.py |-- urls.py |-- api.py | |-- __init__.py `-- views.py |-- __init__.py | |-- pie.py `-- sqlalchemy_api.py | `-- rest.py `-- wsgi.py
  • 33.
  • 34. Introduction to DRF Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs.
  • 35. DRF - Routers ● REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs. ● Types of Routers o SimpleRouter o DefaultRouter o CustomRouters
  • 36. DRF - Parsers ● REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts. ● Types of Parsers o Built-In:  JSONParser, YAMLParser, XMLParser, FormParser, MultiPartParser, FileUploadParser o You can build your own custom parser
  • 37. DRF - ViewSets ● Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'. ● Types of ViewSets: o Built-In:  GenericViewSet, ModelViewSet, ReadOnlyModelViewSet o You can build your own custom ViewSet
  • 38. DRF - Renderers ● REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types.
  • 39. DRF - Renderers ● Built-in Renderers o JSONRenderer, UnicodeJSONRenderer, JSONPRenderer, YAMLRenderer, XMLRenderer, TemplateHTMLRenderer, StaticHTMLRenderer,HTMLFormRenderer, BrowsableAPIRenderer, MultiPartRenderer o Custom Renderers
  • 40. Other Features ● Authorization o BasicAuthorization, TokenAuthorization, SessionAuthorization, OAuthAuthorization, OAuth2Authorization, CustomAuthorization ● Permissions ● Throttling ● Filtering ● Pagination
  • 42.
  • 43. Introduction to Tastypie ● Tastypie is a framework providing boilerplate code to create RESTful APIs ● Depends on Django - cannot stand alone ● Basically involves creating ‘Resource’ oriented classes ● Resources are intermediary between end-user and Django models ● Provides out-of-box authentication, authorization, caching, throttling and serialization
  • 44. Tastypie Request Flow HTTP Request Django URL Resolver check Lookup view for match Check for serialization errors call dispatch dispatch method call HTTP method in allowed list? Authenticate/Authorize Throttle check call actual method
  • 45. Advanced Tastypie ● Bundles - Abstraction to pass data between resources ● Api - Collection of resources ● Resource Fields - Representation of resource (just like Django Fields) ● You can customize authentication, authorization, caching, throttling, validation, serialization ● Learn more at http://django-tastypie.readthedocs.org/
  • 47. Non-Django ORM sources ● What if - we cannot use Django ORM and we need something more advanced? ● Both frameworks have hooks to replace Django ORM ● Tastypie - Extend and override ‘Resource’ methods ● DRF - Extend and override ‘ViewSet’ methods
  • 48. Conclusion (1) ● REST is now the standard for open APIs ● REST is best summed up as verbs + nouns in URLS ● Django app is structured as urls + views + models + stuff to make it easier ● Provides ORM ● Lots of libraries which build off it
  • 49. Conclusion (2) ● DRF documentation is better and well-structured ● DRF is modular, pluggable, easy to understand ● DRF supports web-browsable APIs and oAuth2 ● DRF has better integration with Swagger ● TastyPie is older, can do anything, but is less Django-style
  • 50. The Verdict Description DRF TastyPie Git Commits Web-browsable APIs Yes No Throttling Yes Yes Caching Yes Yes Form Validation No Yes oAuth2 Yes No Documentation Well-structured, easy to find Good, but not good enough Ease of use APIs are Django-like, easier to understand and hence use APIs hard to understand and hence use Swagger Better integration Does integrate, but takes effort

Editor's Notes

  1. My name is Bob Schmoe. I want to find out used cars near me. So I make a RESTful call to this server called foo.bar.com for used cars with a request with my username, and a query saying “nearby”. I get a response back with
  2. We are simply requesting for nearby cars for Bobschmoe but the server somehow knew his zip code and responded back. The server had some state information as to where bobschmoe lived. It was never sent through the payload.
  3. You’re asked to create a service that allows users to add vehicles to your company’s profile. The URL is shown and you’re asked to make a call to the URL to add the vehicle.
  4. A hospital is writing software to back up their patient’s data into a third-party secure medical database. This hospital has seen John Doe before, but his address and medical history have changed. They need to update the customer. They do so by calling http://thirdpartymedical.com/patients?method=updateAddress&patient_id=32543 With an attached JSON payload containing the new data.
  5. Here I’ll open up various files - views and models to give people a look inside.
  6. In Tastypie, the Api gathers together the Resources & provides a nice way to use them as a set. It handles many of the URLconf details for you, provides a helpful “top-level” view to show what endpoints are available & some extra URL resolution juice. from tastypie import fields Validation - FormValidation