Django REST Framework

3.17.1 · active · verified Sun Mar 29

Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs with Django. It simplifies the creation of RESTful services by providing robust serialization, authentication, permission management, and browsable API features. The library is actively maintained, with frequent minor and patch releases, currently at version 3.17.1.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic REST API endpoint using Django REST Framework's Model, Serializer, and ViewSet pattern. It defines a simple `Item` model, a `ModelSerializer` to convert model instances to JSON and vice-versa, and a `ModelViewSet` to handle CRUD operations. A `DefaultRouter` is used to automatically generate URL patterns, simplifying API endpoint configuration. It also includes the necessary Django settings and URL structure for DRF to function.

import os
import django
from django.conf import settings
from django.urls import path, include
from django.db import models

# Minimal Django settings for DRF
settings.configure(
    DEBUG=True,
    SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'django-insecure-DRF-quickstart-secret-key-for-testing'),
    ROOT_URLCONF=__name__,
    INSTALLED_APPS=[
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'rest_framework',
    ],
    DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
)
django.setup()

from rest_framework import routers, serializers, viewsets

# 1. Define a simple Django Model
class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

# 2. Define a Serializer for the Model
class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = '__all__'

# 3. Define a ViewSet for CRUD operations
class ItemViewSet(viewsets.ModelViewSet):
    queryset = Item.objects.all().order_by('-created_at')
    serializer_class = ItemSerializer

# 4. Set up a Router for automatic URL configuration
router = routers.DefaultRouter()
router.register(r'items', ItemViewSet)

# 5. Define URL patterns (mimicking a Django urls.py)
urlpatterns = [
    path('api/', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

# Example usage (run in a Django shell or a test setup)
if __name__ == '__main__':
    # This part would typically be handled by Django's manage.py runserver
    # For demonstration, we'll manually interact.
    # In a real app, you'd run migrations and have a Django server.
    print("DRF Quickstart Example Setup Complete.")
    print("To interact, define URLs and run a Django development server.")
    # Example: Accessing router URLs
    # for url_pattern in router.urls:
    #     print(url_pattern)

    # Note: To run this code interactively outside a full Django project, 
    # you'd need a more involved setup to serve the API, e.g., using a test client.
    # For a minimal runnable example that doesn't require a full Django project setup:
    # This code snippet focuses on the DRF component definitions.
    pass

view raw JSON →