"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
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
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
Graphic showing the stack
- 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
- 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