rest easy with django-rest-framework

Download REST Easy with Django-Rest-Framework

Post on 15-Jul-2015

1.500 views

Category:

Software

4 download

Embed Size (px)

TRANSCRIPT

Django-rest-framework

Rest Easy with Django-rest-frameworkMarcel Chastain (@MarcelChastain)LA Django - 2014-10-28

What well coverWhats REST? Why/when would we use it?REST challengesDjango solutionsInstalling DRFDRF Core Components (and Django counterparts)Building our Demo APICustomizingResources

About restdjango-rest-frameworkBut Im not tiredBut Im not tiredREST stands for Representational State Transfer

All 4 CRUD operations

Uses HTTP requests to:Post data(Create, Update)Read dataDeleteWhy rest?Better than SOAPXML is the stuff of nightmaresUses JSON for data structuresPopular most modern 3rd party web APIs use RESTful endpointsCommon Use-CasesSingle-Page ApplicationsReal-Time ServicesSaaS APIsCreating external APIs for existing sitesMobile AppsWebComponents, Polymer, modular site designModern JS Site Frameworks (Angular, Ember, Backbone, etc)Sounds simple enough!All together now:All together now:We should roll our own! ok just be sure to includeserialization/deserialization

ok just be sure to includeserialization/deserializationparsing

ok just be sure to includeserialization/deserializationparsingmodel introspection

ok just be sure to includeserialization/deserializationparsingmodel introspectionrelationship traversalpluggable authenticationpermissionsurl structureproper HTTP methodspaginationformserror handlingrequest filtersconsistencymaybe some generic viewsrequest throttlingand tests!All together now:

Exactly, wonder woman.Proper solutionsdjango-rest-framework900+ forks304 contributors3k starsThe greatest documentation Ive seen in a library

django-tastypie900+ forks112 contributors2.6k starsDelicious-sounding nameYouve got optionsThe setupDjango-rest-frameworkinstallationpip install djangorestframeworkpip install markdown # optionalpip install django-filter# optional

installation (2)Add to INSTALLED_APPS

# settings.pyINSTALLED_APPS = (...rest_framework,)

installation (3)Include the login/logout views# urls.py

ModelsModels

modelsdjango models

the core componentsdjango-rest-frameworkIn traditional django:Models/QuerysetsClass-Based Views/MixinsGeneric ViewsURLsHTTP RequestsRendered Responsesin DRF:SerializersAPIViews/MixinsViewSetsRoutersHTTP RequestsHTTP Responses1. SerializersSerializers allow complex data to be converted to native Python datatypes that can then be easily rendered in JSON, XML or other content types1.1 SerializersDeclarative syntax, similar to Forms/ModelFormsAutomatically handle single Model instances or Querysets

NoteSerializer.user would have been a plain primary key, but we use a nested serializer301.2 Serializers# using it>>> note = Note.objects.first()>>> serializer = NoteSerializer(note)>>> serializer.data

{u'id': 1, 'body': u'First, do no harm.', 'pub_date': datetime.datetime(2014, 10, 28, 11, 23, 30, tzinfo=), 'title': u'Hippocratic Oath', 'user': { 'id': 1, 'username': u'demo', 'email': u'demo@demo.com' }}2. APIViewsSubclass of Djangos View classSimple - has .get() .post(), etc methods

Some Differences:Requests not normal HTTPRequest (more later)Responses are not normal HTTPResponse (more later)Auth, permissions, throttling done in advance2.1 APIViews

3. viewsetsSimilar to Djangos Generic Views.

A type of Class-Based View that provides actions like .list() and .create() instead of .get() and .post()

Combine the logic for a set of related views into one class, for all the actions youll need to take.3.1 viewsets

3.2 ModelViewsets

4. URL RoutersAutomatic URL routingSimple, quick, consistent way of wiring your view logic to a set of URLs4. URL RoutersAutomatic URL routingSimple, quick, consistent way of wiring your view logic to a set of URLs

5. RequestsIn an APIView or ViewSet, request is a DRF Request.

Incoming JSON data in request is processed just like Form data

Makes request data available as request.DATA (vs .POST)request.FILESrequest.QUERY_PARAMS (vs .GET)6. ResponsesUses content-negotiation to render final content(Hence why built-in API Console shows rich interface to us but would deliver plain JSON to an AJAX request)In traditional django:Models/QuerysetsClass-Based Views/MixinsGeneric ViewsURLsHTTPRequestHTTPResponsein DRF:SerializersAPIViews/MixinsViewSetsURL RoutersDRF RequestDRF ResponseReview:the demodjango-rest-frameworkinstallation (REPO)git clone https://github.com/marcelchastain/drf-demo.git

API Running!

customizingdjango-rest-frameworkCustomizing Viewsquerysetserializer_classfilter_classauthentication_classes (rest_framework.authentication)permission_classes (rest_framework.permissions)parser_classes (rest_framework.parsers)renderer_classes (rest_framework.renderers)throttle_classes (rest_framework.throttling)paginate_by, max_paginate_by

(Defaults for most can be set in settings.py)resourcesdjango-rest-framework47resourcesDocs: http://www.django-rest-framework.orgTutorial: http://www.django-rest-framework.org/#tutorial

IRC: #restframework on irc.freenode.net

StackOverflow: django-rest-framework tag

Author: Tom Christie (@_tomchristie)

Commercial Support: DAB Apps http://dabapps.comRest Easy with Django-rest-frameworkMarcel Chastain (@MarcelChastain)LA Django - 2014-10-28