SlideShare a Scribd company logo
Build and Customize RESTful Web
Services with Django-Tastypie
@gauravtoshniwal
Gaurav Toshniwal
Co-founder, WireddIn Interactive Pvt. Ltd.
(Mobile and Web App development)
Outline of the Talk
 Why REST?
 Why Tastypie?
 Why not Tastypie?
 Basic API setup from a model
 DEMO
 Related Models/ Exclude/ Include/ Serializers
 Ordering/Filtering/Bulk Operations
 Authentication
 Authorization
 Customization (Complex Filters/Hydrate/Dehydrate)
 O & A
About REST
 Client-Server
 Stateless
 Cacheable
 Layered System
 Uniform Interface
About REST: Vocabulary
 GET
 POST
 PUT
 PATCH
 DELETE
About REST: RESTful Web APIs
 A RESTful web API (also called a RESTful web service) is a
web API implemented using HTTP and REST principles. It is
a collection of resources, with four defined aspects:
 the base URI for the web API, such as
http://example.com/resources/
 the Internet media type of the data supported by the web
API. This is often JSON but can be any other valid Internet
media type provided that it is a valid hypertext standard.
 the set of operations supported by the web API using HTTP
methods (e.g., GET, PUT, POST, or DELETE).
 The API must be hypertext driven.
What Is Tastypie?
 "Tastypie is an webservice API framework for Django. It
provides a convenient, yet powerful and highly
customizable, abstraction for creating REST-style
interfaces.”
 Ranked high in Django-Packages ranking algorithm
Why not Tastypie?
Why Tastypie?
 Makes Sense – quick and feature-rich
 Well Tested
 Good features and support, fits well into existing ORM
thinking
 Totally Extensible
 Serialization methods
 Authentication and authorization in-built
 Other features: Throttling
Basic API setup: Define model
from django.db import models
class Todo(models.Model):
todo = models.CharField(max_length=100, blank=False)
done = models.BooleanField("Done",blank=True,
default=False)
def __unicode__(self):
return "%s" % self.todo
Basic API setup: Define Resources
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.serializers import Serializer
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from todo.models import Todo
class TodoResource(ModelResource):
class Meta:
queryset = Todo.objects.all()
resource_name = 'todo’
Basic API setup: Hook up URLs
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from tastypie.api import Api
api = Api(api_name='v1')
from todo.api.resources import TodoResource
api.register(TodoResource())
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
(r'^api/', include(api.urls)),
)
Basic API setup: DEMO
 Schema
 POST demo (create data)
 View data in Admin
 GET demo (retrieve data)
 without format=json
 with format=json
 with format=xml, yaml
 /set/1;5/?format=json
 DELETE demo
Related Models/ Exclude/ Include/
Serializers
class UserTodo(models.Model):
todo = models.CharField(max_length=100, blank=False)
done = models.BooleanField("Done",blank=True,
default=False)
due = models.DateField(blank=True)
created = models.DateField(auto_now_add=True)
user = models.ForeignKey(User)
def __unicode__(self):
return "%s" % self.todo
Related Models/ Exclude/ Include/
Serializers
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
excludes = ['email',
'password',
'is_superuser']
serializer = Serializer(formats=['json'])
class UserTodoResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
queryset = UserTodo.objects.all()
resource_name = 'user_todo'
fields = ['todo', 'user','due']
serializer = Serializer(formats=['json'])
authorization = Authorization()
Exclude fields from API output
Include only these fields
Built-in Authorize everyone for
everything option
Foreign key
To be added:
 Request-response cycle
 Filtering
 Advanced Data preparation (customized logic):
 The Dehydrate Cycle (customize output)
 The Hydrate Cycle (customize input)
 Authentication
 Authorization
Request Response Cycle
Request
• Resource.wrap_view(‘dispatch_list’)
Dispatch_list
dispatch
• Checks
• Allowed methods
• If the class has a method that can handle the request (get_list)
• Is_authenticated
• Is_authorized
• Throttle_check
Get_list
• Obj_get_list
• Build_filters
• Get_objects_list (gets the queryset)
• apply_authorization_limits (to limit the set the user can work with)
• sorting
• pagination
• Full_dehydrate raw data to objects)
Create_response
• Serialization
• Return httpResponse

More Related Content

PPTX
Using WordPress as your application stack
PDF
Action Controller Overview, Season 2
PDF
Getting Started-with-Laravel
PDF
Layouts and Rendering in Rails, Season 2
PDF
Silex: From nothing to an API
PDF
Flask - Backend com Python - Semcomp 18
PPTX
21.search in laravel
KEY
Routing 1, Season 1
Using WordPress as your application stack
Action Controller Overview, Season 2
Getting Started-with-Laravel
Layouts and Rendering in Rails, Season 2
Silex: From nothing to an API
Flask - Backend com Python - Semcomp 18
21.search in laravel
Routing 1, Season 1

What's hot (20)

PDF
深入淺出 MVC
KEY
Rails Antipatterns | Open Session with Chad Pytel
PPTX
Zend framework
KEY
You're Doing It Wrong
PDF
Simplifying Code: Monster to Elegant in 5 Steps
PDF
Complex Sites with Silex
PDF
Desenvolvendo APIs usando Rails - Guru SC 2012
PDF
ACL in CodeIgniter
PDF
Silex Cheat Sheet
PPTX
Cakefest 2010: API Development
PPTX
ADF 2.4.0 And Beyond
PDF
Rails 3 Beautiful Code
PDF
Apache Click
PDF
Teaming up WordPress API with Backbone.js in Titanium
PDF
Codeigniter : Two Step View - Concept Implementation
PDF
Rails 4.0
PPT
Zend - Installation And Sample Project Creation
PDF
devise tutorial - 2011 rubyconf taiwan
PDF
Silex and Twig (PHP Dorset talk)
深入淺出 MVC
Rails Antipatterns | Open Session with Chad Pytel
Zend framework
You're Doing It Wrong
Simplifying Code: Monster to Elegant in 5 Steps
Complex Sites with Silex
Desenvolvendo APIs usando Rails - Guru SC 2012
ACL in CodeIgniter
Silex Cheat Sheet
Cakefest 2010: API Development
ADF 2.4.0 And Beyond
Rails 3 Beautiful Code
Apache Click
Teaming up WordPress API with Backbone.js in Titanium
Codeigniter : Two Step View - Concept Implementation
Rails 4.0
Zend - Installation And Sample Project Creation
devise tutorial - 2011 rubyconf taiwan
Silex and Twig (PHP Dorset talk)
Ad

Similar to Django Tastypie 101 (20)

PDF
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
PPTX
Designing CakePHP plugins for consuming APIs
PPTX
Mastering-ASPNET-Web-API-and-RESTful-Patterns.pptx
PPTX
Web api
PPTX
Testwarez 2013 - Warsztat SoapUI
PDF
Crafting [Better] API Clients
ODP
Django for Beginners
ODP
Introduction to Django
PDF
Webservices in SalesForce (part 1)
PDF
Federico Feroldi - Scala microservices
PPTX
Web API with ASP.NET MVC by Software development company in india
PPTX
Standards of rest api
PPTX
Best Practices for Architecting a Pragmatic Web API.
PDF
ASP.NET Core Web API documentation web application
PPTX
Writing HTML5 Web Apps using Backbone.js and GAE
PPTX
A Minimalist’s Attempt at Building a Distributed Application
PPT
Getting Started with Zend Framework
PPTX
Swift LA Meetup at eHarmony- What's New in Swift 2.0
PPTX
Api testing
PDF
The Role of Python in SPAs (Single-Page Applications)
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Designing CakePHP plugins for consuming APIs
Mastering-ASPNET-Web-API-and-RESTful-Patterns.pptx
Web api
Testwarez 2013 - Warsztat SoapUI
Crafting [Better] API Clients
Django for Beginners
Introduction to Django
Webservices in SalesForce (part 1)
Federico Feroldi - Scala microservices
Web API with ASP.NET MVC by Software development company in india
Standards of rest api
Best Practices for Architecting a Pragmatic Web API.
ASP.NET Core Web API documentation web application
Writing HTML5 Web Apps using Backbone.js and GAE
A Minimalist’s Attempt at Building a Distributed Application
Getting Started with Zend Framework
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Api testing
The Role of Python in SPAs (Single-Page Applications)
Ad

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPT
Teaching material agriculture food technology
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Big Data Technologies - Introduction.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Approach and Philosophy of On baking technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Empathic Computing: Creating Shared Understanding
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Electronic commerce courselecture one. Pdf
Assigned Numbers - 2025 - Bluetooth® Document
Dropbox Q2 2025 Financial Results & Investor Presentation
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
NewMind AI Weekly Chronicles - August'25-Week II
Teaching material agriculture food technology
The Rise and Fall of 3GPP – Time for a Sabbatical?
Building Integrated photovoltaic BIPV_UPV.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Unlocking AI with Model Context Protocol (MCP)
Advanced methodologies resolving dimensionality complications for autism neur...
Big Data Technologies - Introduction.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Approach and Philosophy of On baking technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Empathic Computing: Creating Shared Understanding

Django Tastypie 101

  • 1. Build and Customize RESTful Web Services with Django-Tastypie @gauravtoshniwal Gaurav Toshniwal Co-founder, WireddIn Interactive Pvt. Ltd. (Mobile and Web App development)
  • 2. Outline of the Talk  Why REST?  Why Tastypie?  Why not Tastypie?  Basic API setup from a model  DEMO  Related Models/ Exclude/ Include/ Serializers  Ordering/Filtering/Bulk Operations  Authentication  Authorization  Customization (Complex Filters/Hydrate/Dehydrate)  O & A
  • 3. About REST  Client-Server  Stateless  Cacheable  Layered System  Uniform Interface
  • 4. About REST: Vocabulary  GET  POST  PUT  PATCH  DELETE
  • 5. About REST: RESTful Web APIs  A RESTful web API (also called a RESTful web service) is a web API implemented using HTTP and REST principles. It is a collection of resources, with four defined aspects:  the base URI for the web API, such as http://example.com/resources/  the Internet media type of the data supported by the web API. This is often JSON but can be any other valid Internet media type provided that it is a valid hypertext standard.  the set of operations supported by the web API using HTTP methods (e.g., GET, PUT, POST, or DELETE).  The API must be hypertext driven.
  • 6. What Is Tastypie?  "Tastypie is an webservice API framework for Django. It provides a convenient, yet powerful and highly customizable, abstraction for creating REST-style interfaces.”  Ranked high in Django-Packages ranking algorithm
  • 8. Why Tastypie?  Makes Sense – quick and feature-rich  Well Tested  Good features and support, fits well into existing ORM thinking  Totally Extensible  Serialization methods  Authentication and authorization in-built  Other features: Throttling
  • 9. Basic API setup: Define model from django.db import models class Todo(models.Model): todo = models.CharField(max_length=100, blank=False) done = models.BooleanField("Done",blank=True, default=False) def __unicode__(self): return "%s" % self.todo
  • 10. Basic API setup: Define Resources from tastypie.resources import ModelResource from tastypie import fields from tastypie.serializers import Serializer from tastypie.constants import ALL, ALL_WITH_RELATIONS from todo.models import Todo class TodoResource(ModelResource): class Meta: queryset = Todo.objects.all() resource_name = 'todo’
  • 11. Basic API setup: Hook up URLs from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from tastypie.api import Api api = Api(api_name='v1') from todo.api.resources import TodoResource api.register(TodoResource()) urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), (r'^api/', include(api.urls)), )
  • 12. Basic API setup: DEMO  Schema  POST demo (create data)  View data in Admin  GET demo (retrieve data)  without format=json  with format=json  with format=xml, yaml  /set/1;5/?format=json  DELETE demo
  • 13. Related Models/ Exclude/ Include/ Serializers class UserTodo(models.Model): todo = models.CharField(max_length=100, blank=False) done = models.BooleanField("Done",blank=True, default=False) due = models.DateField(blank=True) created = models.DateField(auto_now_add=True) user = models.ForeignKey(User) def __unicode__(self): return "%s" % self.todo
  • 14. Related Models/ Exclude/ Include/ Serializers class UserResource(ModelResource): class Meta: queryset = User.objects.all() resource_name = 'user' excludes = ['email', 'password', 'is_superuser'] serializer = Serializer(formats=['json']) class UserTodoResource(ModelResource): user = fields.ForeignKey(UserResource, 'user') class Meta: queryset = UserTodo.objects.all() resource_name = 'user_todo' fields = ['todo', 'user','due'] serializer = Serializer(formats=['json']) authorization = Authorization() Exclude fields from API output Include only these fields Built-in Authorize everyone for everything option Foreign key
  • 15. To be added:  Request-response cycle  Filtering  Advanced Data preparation (customized logic):  The Dehydrate Cycle (customize output)  The Hydrate Cycle (customize input)  Authentication  Authorization
  • 16. Request Response Cycle Request • Resource.wrap_view(‘dispatch_list’) Dispatch_list dispatch • Checks • Allowed methods • If the class has a method that can handle the request (get_list) • Is_authenticated • Is_authorized • Throttle_check Get_list • Obj_get_list • Build_filters • Get_objects_list (gets the queryset) • apply_authorization_limits (to limit the set the user can work with) • sorting • pagination • Full_dehydrate raw data to objects) Create_response • Serialization • Return httpResponse

Editor's Notes

  • #6: Graphic showing the stack
  • #10: - Define django model - models.py - register the app in settings.py - Create an admin interface, add dummy data - enable in urls.py - enable in settings.py - create admin.py - add dummy data
  • #13: - DEMO - demo without format=json - demo with format=json - demo with format=xml, yaml - /schema/?format=json - /set/1;5/?format=json - POST demo - DELETE demo