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.
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.
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)
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
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
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
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.
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.
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.
Here I’ll open up various files - views and models to give people a look inside.
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