730 likes | 976 Views
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.
E N D
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. • An architectural style for distributed systems just like the web • REST is not tied to the web, but it's almost always implemented as such, and was inspired by HTTP • 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 • Uses RESTful calls to communicate between mobile devices and car: http://docs.timdorr.apiary.io/
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 • Client-Server • Stateless Server • Cache • Uniform Interface • Layered System • Code-On-Demand
REST Characteristics • Client-Server Model: Pull Based (not event driven) system • Client - Sends requests to a server and awaits a response from the server. • Server - Provides a service to multiple clients. Receives requests and provides a response for the information that the client requested.
REST Characteristics • Stateless Server • Each request to the server must contain all of the information necessary for the server to understand the request. • 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 • 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 • Resource Identifier - URL / URI • http://twitter.com/#!/jack/status/20 • Resource Representation and Manipulation • Whatever comes back that represents the resource identified by the URL. We can manipulate the resource directly from the URL. • 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 • 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 • Should be able to accommodate extra layers like proxy servers, firewalls, gateways, caching system • (this is why HTTP is most often used)
REST Characteristics • Code-on-Demand • 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 • https://blog.apigee.com/detail/api_design_ruminating_over_rest • A Beginner's Guide to HTTP and REST • http://code.tutsplus.com/tutorials/a-beginners-guide-to-http-and-rest--net-16340 • HATEOAS • https://www.youtube.com/watch?v=6UXc71O7htc
HTTP • Hypertext Transfer Protocol • Roy Fielding used REST to implement HTTP 1.1 • The protocol that is used to manipulate remote resources. • We can use HTTP Verbs to manipulate these resources.
CRUD (Create, Read, Update, 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 • 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 • easy to change your frontend client without touching your API • can add multiple clients (web, mobile, desktop app, batch process, etc) with no logic changes • 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 Request: Method: GETRequest Payload: { "username" : "bobschmoe", "query" : "nearby" } Response:{ "results” : [{ "car_id" : "ABC001”, "make” : "Honda”, "model” : "Accord” }, { "car_id” : "ABC001”, "make” : "Honda”, "model” : "Accord” }], "zip": "11040" } URL: http://foo.bar.com/cars/used/
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 Request: Method: POSTRequest Payload: { "resource" : "vehicle", "method" : "addVehicle", "year" : "2014", "make" : "Honda", "model" : "Accord", "trim" : "EX-L", } Response:{ "resource_id" : "ABC00234", } URL: http://profile.mycompany.com/api/
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 Request: Method: POSTRequest Payload: { "address" : "123 Main Street", "city" : "Lake Success", "state" : "NY", } Response:{ "success" : "true" } URL: http://mymeds.com/patients?method=updateAddress&patient_id=3254
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 Browser Django 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 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), ) GET note/3 GET note/3 Response - (e.g. JSON text)
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 • SimpleRouter • DefaultRouter • 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 • Built-In: • JSONParser, YAMLParser, XMLParser, FormParser, MultiPartParser, FileUploadParser • 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: • Built-In: • GenericViewSet, ModelViewSet, ReadOnlyModelViewSet • 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 • JSONRenderer, UnicodeJSONRenderer, JSONPRenderer, YAMLRenderer, XMLRenderer, TemplateHTMLRenderer, StaticHTMLRenderer,HTMLFormRenderer, BrowsableAPIRenderer, MultiPartRenderer • Custom Renderers
Other Features • Authorization • BasicAuthorization, TokenAuthorization, SessionAuthorization, OAuthAuthorization, OAuth2Authorization, CustomAuthorization • Permissions • Throttling • Filtering • Pagination
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 dispatch method call Django URL Resolver check HTTP method in allowed list? Lookup view for match Authenticate/Authorize Check for serialization errors Throttle check call dispatch 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/
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