Upload
ashish-gore
View
3.482
Download
7
Embed Size (px)
DESCRIPTION
Slides from the Long Island Python Meetup http://www.meetup.com/li-python/events/175793552/
Citation preview
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
o Code-On-Demand
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.
● API Design: Ruminating Over RESTo https://blog.apigee.com/detail/api_design_ruminat
ing_over_rest
● A Beginner's Guide to HTTP and RESTo http://code.tutsplus.com/tutorials/a-beginners-
guide-to-http-and-rest--net-16340
● HATEOASo https://www.youtube.com/watch?v=6UXc71O7htc
More Information
HTTP
● Hypertext Transfer Protocolo Roy Fielding used REST to implement HTTP 1.1o 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 APIo can add multiple clients (web, mobile, desktop app, batch
process, etc) with no logic changeso 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.
Request:Method: GETRequest Payload:{
"username" : "bobschmoe",
"query" : "nearby"
}
Example 1: Find Cars for User
URL: http://foo.bar.com/cars/used/
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.
Request:Method: POSTRequest Payload:{
"resource" : "vehicle",
"method" : "addVehicle",
"year" : "2014",
"make" : "Honda",
"model" : "Accord",
"trim" : "EX-L",
}
Example 2: Add Vehicle to Company Profile
URL: http://profile.mycompany.com/api/
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.
Request:Method: POSTRequest Payload:{
"address" : "123 Main Street",
"city" : "Lake Success",
"state" : "NY",
}
Example #3: Modifying Patient Information
URL: http://mymeds.com/patients?method=updateAddress&patient_id=3254
Response:{
"success" : "true"
}
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.
Example #3: Modifying Patient Information
Django Request-Response Cycle
Browser
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
GET note/3
Response - (e.g. JSON text)
Demo Structure Overview
Project Structurenotematic3000
|----------------------------------------------- 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 Settingsfrom 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 Structurenotematic3000
|----------------------------------------------- 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 Routerso SimpleRoutero DefaultRoutero 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 Parserso 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
● REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types.
DRF - Renderers
● Built-in Rendererso JSONRenderer, UnicodeJSONRenderer,
JSONPRenderer, YAMLRenderer, XMLRenderer, TemplateHTMLRenderer, StaticHTMLRenderer,HTMLFormRenderer, BrowsableAPIRenderer, MultiPartRenderer
o Custom Renderers
DRF - Renderers
Other Features
● Authorizationo 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
Django URL Resolver check
HTTP Request
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 VerdictDescription 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