django-tastypie

raw JSON →
0.15.1 verified Mon Apr 27 auth: no python

A flexible & capable API layer for Django. Current version 0.15.1, maintained but with infrequent releases.

pip install django-tastypie
error ModuleNotFoundError: No module named 'tastypie'
cause django-tastypie not installed or not in environment.
fix
Run: pip install django-tastypie
error AttributeError: 'NoneType' object has no attribute 'items'
cause Often due to missing 'queryset' in Meta class of ModelResource.
fix
Add 'queryset = MyModel.objects.all()' to the Meta class.
error ImproperlyConfigured: The 'api_name' argument must be specified.
cause Api instantiated without api_name.
fix
Use Api(api_name='v1') or pass the name parameter.
gotcha ModelResource.Meta.queryset is required and must be a QuerySet, not a manager.
fix Use MyModel.objects.all() instead of MyModel.objects.
gotcha Serialization of many-to-many fields requires explicit declaration in the resource fields.
fix Add fields = ['m2m_field'] to the Meta class.
gotcha Tastypie does NOT support Django's new-style middleware (MIDDLEWARE setting). You must use MIDDLEWARE_CLASSES if you need tastypie middleware.
fix Use MIDDLEWARE_CLASSES or upgrade to 0.15.0+ which adds partial compatibility.
gotcha The 'dehydrate' and 'hydrate' methods are for modifying serialized/deserialized data, not for validation.
fix Use 'is_valid' or custom validation in 'obj_create'/'obj_update'.
deprecated The 'authentication' and 'authorization' params in Meta are being replaced by class-based configurations in future releases.
fix Check docs for updated patterns; currently both work.

Minimal setup: define a ModelResource, register it on an Api instance, and include the urls.

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
import django
django.setup()

from tastypie.api import Api
from tastypie.resources import ModelResource
from myapp.models import MyModel

class MyModelResource(ModelResource):
    class Meta:
        queryset = MyModel.objects.all()
        resource_name = 'mymodel'
        allowed_methods = ['get', 'post', 'put', 'delete']
        authentication = ApiKeyAuthentication()
        authorization = DjangoAuthorization()

api = Api(api_name='v1')
api.register(MyModelResource())

# Then include in urls.py as: urlpatterns = [path('api/', include(api.urls))]