### Initialize Django Project and App Environment Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/quickstart.md Commands to create a project directory, set up a virtual environment, install Django REST Framework, and initialize the project structure. ```bash (Linux/macOS) # Create the project directory mkdir tutorial cd tutorial # Create a virtual environment to isolate our package dependencies locally python3 -m venv .venv source .venv/bin/activate # Install Django and Django REST framework into the virtual environment pip install djangorestframework # Set up a new project with a single application django-admin startproject tutorial . # Note the trailing '.' character cd tutorial django-admin startapp quickstart cd .. ``` ```bash (Windows) # Create the project directory mkdir tutorial cd tutorial # Create a virtual environment to isolate our package dependencies locally python3 -m venv .venv source .venv\Scripts\activate # Install Django and Django REST framework into the virtual environment pip install djangorestframework # Set up a new project with a single application django-admin startproject tutorial . # Note the trailing '.' character cd tutorial django-admin startapp quickstart cd .. ``` -------------------------------- ### Start Django Development Server for API Testing Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/quickstart.md Launches the Django development server to run and test the REST Framework API locally. The server runs on the default address http://127.0.0.1:8000 and allows access to all configured API endpoints. ```bash python manage.py runserver ``` -------------------------------- ### Setup Virtual Environment and Install Dependencies Source: https://github.com/encode/django-rest-framework/blob/main/docs/community/contributing.md Create and activate a Python virtual environment, then install Django REST Framework in development mode with all development dependencies. This prepares the environment for running tests. ```bash python3 -m venv env source env/bin/activate pip install -e . --group dev ``` -------------------------------- ### Install Django REST Framework in INSTALLED_APPS Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/quickstart.md Registers the Django REST Framework application in the Django project's INSTALLED_APPS setting. This enables all REST framework features and makes its URLs and templates available to the project. ```text INSTALLED_APPS = [ ..., 'rest_framework', ] ``` -------------------------------- ### Sync Database and Create Superuser Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/quickstart.md Commands to apply initial database migrations and create an administrative user for API authentication and management. ```bash python manage.py migrate python manage.py createsuperuser --username admin --email admin@example.com ``` -------------------------------- ### Test Django REST Framework API with httpie Command Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/quickstart.md Demonstrates testing a Django REST Framework API endpoint using httpie, a user-friendly command-line HTTP client. The example shows authentication with the -a flag and returns the same paginated user data with formatted HTTP response headers. ```bash http -a admin http://127.0.0.1:8000/users/ http: password for admin@127.0.0.1:8000:: $HTTP/1.1 200 OK ... { "count": 1, "next": null, "previous": null, "results": [ { "email": "admin@example.com", "groups": [], "url": "http://127.0.0.1:8000/users/1/", "username": "admin" } ] } ``` -------------------------------- ### Test Django REST Framework API with curl Command Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/quickstart.md Demonstrates testing a Django REST Framework API endpoint using curl with basic authentication and JSON response formatting. The example queries the users endpoint and returns paginated results with user information including URL, username, email, and groups. ```bash curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/ Enter host password for user 'admin': { "count": 1, "next": null, "previous": null, "results": [ { "url": "http://127.0.0.1:8000/users/1/", "username": "admin", "email": "admin@example.com", "groups": [] } ] } ``` -------------------------------- ### Create ViewSets for User and Group API Endpoints Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/quickstart.md Implements ModelViewSets to handle the logic for viewing and editing User and Group instances, including default ordering and authentication requirements. ```python from django.contrib.auth.models import Group, User from rest_framework import permissions, viewsets from tutorial.quickstart.serializers import GroupSerializer, UserSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by("-date_joined") serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all().order_by("name") serializer_class = GroupSerializer permission_classes = [permissions.IsAuthenticated] ``` -------------------------------- ### Install and Configure DjangoFilterBackend in Django Settings Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/filtering.md Shows the installation and configuration steps for django-filter library integration with Django REST Framework. This includes installing the package via pip, adding it to INSTALLED_APPS, and configuring the DEFAULT_FILTER_BACKENDS in REST_FRAMEWORK settings for global application across all views. ```bash pip install django-filter ``` ```python INSTALLED_APPS = [ ..., 'django_filters', ... ] ``` ```python REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } ``` -------------------------------- ### Install and Configure XML Parser Support Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/parsers.md Details the setup for XML support in Django REST Framework using the djangorestframework-xml package. Includes the installation command and the global configuration required in the Django settings file. ```bash $ pip install djangorestframework-xml ``` ```python REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': [ 'rest_framework_xml.parsers.XMLParser', ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework_xml.renderers.XMLRenderer', ], } ``` -------------------------------- ### Configure API URL Routing with DefaultRouter Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/quickstart.md Sets up automatic URL routing for the API by registering ViewSets with a DefaultRouter and including them in the project's URL patterns. ```python from django.urls import include, path from rest_framework import routers from tutorial.quickstart import views router = routers.DefaultRouter() router.register(r"users", views.UserViewSet) router.register(r"groups", views.GroupViewSet) # Wire up our API using automatic URL routing. ``` -------------------------------- ### Install Project Dependencies via Pip Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/1-serialization.md Installs the core requirements for the tutorial including Django, Django REST Framework, and Pygments for code syntax highlighting. ```bash pip install django pip install djangorestframework pip install pygments ``` -------------------------------- ### Build Documentation with MkDocs Source: https://github.com/encode/django-rest-framework/blob/main/docs/community/contributing.md Build the REST framework documentation from Markdown source files into static HTML. Installs MkDocs and generates the site directory with compiled documentation. ```bash pip install mkdocs mkdocs build ``` -------------------------------- ### Define Hyperlinked Serializers for User and Group Models Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/quickstart.md Defines serializers using HyperlinkedModelSerializer to represent User and Group data as JSON with RESTful hyperlinking. ```python from django.contrib.auth.models import Group, User from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ["url", "username", "email", "groups"] class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ["url", "name"] ``` -------------------------------- ### Install HTTPie via pip Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/1-serialization.md This command uses pip, Python's package installer, to install HTTPie. HTTPie is a user-friendly command-line HTTP client that simplifies making requests to web APIs, offering a more intuitive syntax than curl. ```bash pip install httpie ``` -------------------------------- ### GET /hello-world Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/views.md Illustrates a simple function-based API view in Django REST Framework that responds to GET requests, returning a static greeting message. This example uses the default renderer, parser, and authentication settings. ```APIDOC ## GET /hello-world ### Description This endpoint demonstrates a basic function-based view in Django REST Framework. It is configured to respond to GET requests and returns a predefined JSON object as a greeting. This view uses the default DRF settings for rendering, parsing, and authentication. ### Method GET ### Endpoint /hello-world (Assumed endpoint path for demonstration) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (No request body required for GET) ### Response #### Success Response (200) - **message** (string) - A simple greeting message. #### Response Example { "message": "Hello, world!" } ``` -------------------------------- ### Install Pre-commit Hooks for Code Style Source: https://github.com/encode/django-rest-framework/blob/main/docs/community/contributing.md Install and configure pre-commit hooks to automatically check code against PEP 8 style conventions. This ensures contributions follow project standards before committing changes. ```bash python -m pip install pre-commit pre-commit install ``` -------------------------------- ### Apply PrettyPrint Syntax Highlighting to Code Blocks Source: https://github.com/encode/django-rest-framework/blob/main/docs/theme/main.html Subscribes to document changes and applies PrettyPrint styling classes to all code blocks within
tags. This enables automatic syntax highlighting for code examples displayed in the documentation. The script adds 'prettyprint' and 'well' CSS classes to parent elements and triggers the PrettyPrint renderer.
```javascript
document$.subscribe(function() {
document.querySelectorAll('pre code').forEach(code => {
code.parentElement.classList.add('prettyprint', 'well');
});
prettyPrint();
});
```
--------------------------------
### Configure URL Patterns with Router and Authentication in Django REST Framework
Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/quickstart.md
Sets up URL routing for a Django REST Framework API using a router to automatically generate URL patterns from viewsets, and includes authentication URLs for the browsable API. The router simplifies URL configuration by automatically generating endpoints for registered viewsets.
```python
urlpatterns = [
path("", include(router.urls)),
path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),
]
```
--------------------------------
### GET /api/products
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/filtering.md
Retrieves a list of products with support for equality-based filtering on specific fields like category and stock status.
```APIDOC
## GET /api/products
### Description
Returns a list of all products. Supports filtering by category and stock availability using query parameters via DjangoFilterBackend.
### Method
GET
### Endpoint
/api/products
### Parameters
#### Query Parameters
- **category** (string) - Optional - Filter products by category name.
- **in_stock** (boolean) - Optional - Filter products based on whether they are in stock.
### Request Example
GET /api/products?category=clothing&in_stock=True
### Response
#### Success Response (200)
- **results** (array) - A list of product objects.
- **id** (integer) - The unique identifier for the product.
- **category** (string) - The category of the product.
- **in_stock** (boolean) - Indicates if the product is currently available.
#### Response Example
[
{
"id": 101,
"name": "Denim Jacket",
"category": "clothing",
"in_stock": true
}
]
```
--------------------------------
### Configure Interactive API Documentation in Django URLconf
Source: https://github.com/encode/django-rest-framework/blob/main/docs/community/3.6-announcement.md
Example of how to integrate the interactive API documentation into a Django project's URL configuration using the include_docs_urls function. This requires the coreapi library to be installed.
```python
from rest_framework.documentation import include_docs_urls
API_TITLE = 'API title'
API_DESCRIPTION = '...'
urlpatterns = [
...
path('docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))
]
```
--------------------------------
### GET /
Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/5-relationships-and-hyperlinked-apis.md
Provides a single entry point to the API, returning hyperlinked URLs for 'users' and 'snippets' resources to improve discoverability and cohesion.
```APIDOC
## GET /
### Description
This endpoint serves as the root of the API, providing fully-qualified, hyperlinked URLs to the main resources: 'users' and 'snippets'. It enhances API discoverability by offering a central entry point.
### Method
GET
### Endpoint
/
### Parameters
#### Path Parameters
- None
#### Query Parameters
- **format** (string) - Optional - Specifies the desired response format (e.g., 'json', 'api').
#### Request Body
- None
### Request Example
```json
{}
```
### Response
#### Success Response (200)
- **users** (string) - A fully-qualified URL to the user list endpoint.
- **snippets** (string) - A fully-qualified URL to the snippet list endpoint.
#### Response Example
```json
{
"users": "http://example.com/users/",
"snippets": "http://example.com/snippets/"
}
```
```
--------------------------------
### Example of Versioned API Request and JSON Response
Source: https://github.com/encode/django-rest-framework/blob/main/docs/community/3.1-announcement.md
Illustrates a GET request to a versioned endpoint and the resulting JSON response where hyperlinked fields are prefixed with the correct version segment.
```json
GET http://example.org/v2/accounts/10
{
"account_name": "europa",
"users": [
"http://example.org/v2/users/12",
"http://example.org/v2/users/54",
"http://example.org/v2/users/87"
]
}
```
--------------------------------
### Install Django REST Framework via pip
Source: https://github.com/encode/django-rest-framework/blob/main/docs/index.md
Install Django REST Framework and optional packages for enhanced functionality including Markdown support for the browsable API and filtering capabilities. Uses pip package manager to install from PyPI.
```bash
pip install djangorestframework
pip install markdown # Markdown support for the browsable API.
pip install django-filter # Filtering support
```
--------------------------------
### HTTP Request with Accept-Language Header
Source: https://github.com/encode/django-rest-framework/blob/main/docs/community/3.1-announcement.md
Example HTTP GET request demonstrating how to specify a preferred language using the Accept-Language header. The server will respond with error messages in the requested language if supported.
```http
GET /api/users HTTP/1.1
Accept: application/xml
Accept-Language: es-es
Host: example.org
```
--------------------------------
### Install djangorestframework-xml Package
Source: https://github.com/encode/django-rest-framework/blob/main/docs/community/3.1-announcement.md
Command to install the separately maintained XML rendering package for Django REST Framework. Required after the package was moved out of core.
```bash
pip install djangorestframework-xml
```
--------------------------------
### Run Tests Against Multiple Python and Django Versions
Source: https://github.com/encode/django-rest-framework/blob/main/docs/community/contributing.md
Use tox to automatically test against all supported versions of Python and Django. Install tox globally first, then run to verify compatibility across environments.
```bash
tox
```
--------------------------------
### Example HTTP OPTIONS Response in Django REST Framework
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/metadata.md
This example demonstrates the default information returned by Django REST Framework for an HTTP OPTIONS request. It includes allowed methods, content types for rendering and parsing, and detailed action descriptions for available HTTP methods like POST.
```http
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
{
"name": "To Do List",
"description": "List existing 'To Do' items, or create a new item.",
"renders": [
"application/json",
"text/html"
],
"parses": [
"application/json",
"application/x-www-form-urlencoded",
"multipart/form-data"
],
"actions": {
"POST": {
"note": {
"type": "string",
"required": false,
"read_only": false,
"label": "title",
"max_length": 100
}
}
}
}
```
--------------------------------
### Install Django REST Framework OAuth Package
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/authentication.md
Install the djangorestframework-oauth package to provide OAuth1 and OAuth2 support for REST framework. This package is maintained as a third-party alternative to the previously built-in OAuth support.
```bash
pip install djangorestframework-oauth
```
--------------------------------
### Django Template Tags and Filters Example
Source: https://github.com/encode/django-rest-framework/blob/main/rest_framework/templates/rest_framework/admin/dict_value.html
This snippet demonstrates the `load rest_framework` tag, an empty `for` loop, and the `format_value` filter applied to variables `k` and `v`.
```Django Template
{% load rest_framework %} {% for k, v in value|items %} {% endfor %}
{{ k|format_value }}
{{ v|format_value }}
```
--------------------------------
### Test token authenticated API with curl
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/authentication.md
Command-line example using curl to test a token-authenticated REST Framework API endpoint. Includes the Authorization header with the token key for authentication.
```bash
curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'
```
--------------------------------
### Example GET Request for LimitOffsetPagination in DRF
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/pagination.md
Illustrates a client-side GET request using the LimitOffsetPagination style, specifying a 'limit' for the number of items and an 'offset' for the starting position.
```http
GET https://api.example.org/accounts/?limit=100&offset=400
```
--------------------------------
### Serve Documentation Preview
Source: https://github.com/encode/django-rest-framework/blob/main/docs/community/contributing.md
Build and serve the documentation locally in a browser window for live preview. Useful for reviewing documentation changes during development.
```bash
mkdocs serve
```
--------------------------------
### Initialize Django Project and Snippets App
Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/1-serialization.md
Commands to create a new Django project named 'tutorial' and a specific application named 'snippets' to handle the API logic.
```bash
cd ~
django-admin startproject tutorial
cd tutorial
python manage.py startapp snippets
```
--------------------------------
### GET /api/purchased-products
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/filtering.md
Returns a list of products that the authenticated user has purchased, with support for optional filtering.
```APIDOC
## GET /api/purchased-products
### Description
Returns a list of all the products that the authenticated user has ever purchased. This endpoint overrides the initial queryset to ensure users only see their own data.
### Method
GET
### Endpoint
/api/purchased-products
### Parameters
#### Path Parameters
None
#### Query Parameters
- **filter** (string) - Optional - Custom filters defined in the ProductFilter class.
### Request Example
GET /api/purchased-products
### Response
#### Success Response (200)
- **id** (integer) - Product ID
- **name** (string) - Product Name
- **purchase_date** (string) - Date of purchase
#### Response Example
[
{
"id": 42,
"name": "Wireless Headphones",
"purchase_date": "2023-10-15"
}
]
```
--------------------------------
### Create and Activate Virtual Environment
Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/1-serialization.md
Initializes a Python virtual environment to isolate project dependencies. Includes activation commands for Linux, macOS, and Windows Bash environments.
```bash
python3 -m venv .venv
source .venv/bin/activate
```
```bash
python3 -m venv .venv
source .venv\Scripts\activate
```
--------------------------------
### Setup Django OAuth Toolkit for OAuth 2.0 Authentication
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/authentication.md
Install and configure the Django OAuth Toolkit to enable OAuth 2.0 support in your project. This requires installing the package via pip and updating the Django settings to include the provider and authentication class.
```bash
pip install django-oauth-toolkit
```
```python
INSTALLED_APPS = [
...
'oauth2_provider',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
]
}
```
--------------------------------
### Test Django REST Framework API with format suffixes using HTTPie
Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/2-requests-and-responses.md
Demonstrates testing the API using HTTPie command-line tool to verify format suffix support. Shows how to request different response formats using URL suffixes (.json, .api) and Accept headers, and how to POST data using form data or JSON content types.
```bash
# List all snippets
http http://127.0.0.1:8000/snippets/
# Request specific format using Accept header
http http://127.0.0.1:8000/snippets/ Accept:application/json
http http://127.0.0.1:8000/snippets/ Accept:text/html
# Request specific format using URL suffix
http http://127.0.0.1:8000/snippets.json
http http://127.0.0.1:8000/snippets.api
# POST using form data
http --form POST http://127.0.0.1:8000/snippets/ code="print(123)"
# POST using JSON
http --json POST http://127.0.0.1:8000/snippets/ code="print(456)"
# Debug request headers
http --debug POST http://127.0.0.1:8000/snippets/ code="print(789)"
```
--------------------------------
### Set up ReDoc HTML template for OpenAPI schema visualization
Source: https://github.com/encode/django-rest-framework/blob/main/docs/topics/documenting-your-api.md
Creates a minimal HTML template that renders an OpenAPI schema using ReDoc. The template includes responsive design meta tags, Google Fonts for typography, and the ReDoc standalone bundle from CDN. Save as 'redoc.html' in your Django templates folder.
```html
ReDoc
```
--------------------------------
### Internationalized API request and response example
Source: https://github.com/encode/django-rest-framework/blob/main/docs/topics/internationalization.md
Demonstrates an HTTP GET request using the Accept-Language header and the resulting translated error response (406 Not Acceptable) in Spanish.
```http
GET /api/users HTTP/1.1
Accept: application/xml
Accept-Language: es-es
Host: example.org
HTTP/1.0 406 NOT ACCEPTABLE
{"detail": "No se ha podido satisfacer la solicitud de cabecera de Accept."}
```
--------------------------------
### Create and Apply Database Migrations
Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/1-serialization.md
Generates the SQL migration files for the snippets model and applies them to the database schema.
```bash
python manage.py makemigrations snippets
python manage.py migrate snippets
```
--------------------------------
### Filter QuerySet by URL Query Parameters in Django REST Framework
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/filtering.md
Shows how to dynamically filter a queryset based on optional GET parameters provided in the request URL using self.request.query_params.
```python
class PurchaseList(generics.ListAPIView):
serializer_class = PurchaseSerializer
def get_queryset(self):
"""
Optionally restricts the returned purchases to a given user,
by filtering against a `username` query parameter in the URL.
"""
queryset = Purchase.objects.all()
username = self.request.query_params.get('username')
if username is not None:
queryset = queryset.filter(purchaser__username=username)
return queryset
```
--------------------------------
### GET /accounts/ (LimitOffsetPagination)
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/pagination.md
Retrieves a paginated list of accounts using limit and offset query parameters. The limit specifies the maximum number of items to return, and the offset indicates the starting position.
```APIDOC
## GET /accounts/
### Description
Retrieves a paginated list of accounts using limit and offset query parameters. The limit specifies the maximum number of items to return, and the offset indicates the starting position of the query in relation to the complete set of unpaginated items.
### Method
GET
### Endpoint
/accounts/
### Parameters
#### Path Parameters
- No path parameters.
#### Query Parameters
- **limit** (integer) - Optional - The maximum number of items to return. If not provided, `default_limit` (or `PAGE_SIZE`) is used.
- **offset** (integer) - Optional - The starting position of the query. Defaults to 0.
#### Request Body
- No request body.
### Request Example
```
GET https://api.example.org/accounts/?limit=100&offset=400
```
### Response
#### Success Response (200)
- **count** (integer) - The total number of items available.
- **next** (string) - URL for the next page of results, or `null` if no next page.
- **previous** (string) - URL for the previous page of results, or `null` if no previous page.
- **results** (array) - An array of account objects.
#### Response Example
```json
{
"count": 1023,
"next": "https://api.example.org/accounts/?limit=100&offset=500",
"previous": "https://api.example.org/accounts/?limit=100&offset=300",
"results": [
// ... account objects ...
]
}
```
```
--------------------------------
### Register Apps in Django Settings
Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/1-serialization.md
Configuration required in tutorial/settings.py to enable Django REST Framework and the newly created snippets application.
```python
INSTALLED_APPS = [
...
'rest_framework',
'snippets',
]
```
--------------------------------
### Run Tests with Quiet Output
Source: https://github.com/encode/django-rest-framework/blob/main/docs/community/contributing.md
Execute tests with concise output formatting using the -q flag. Useful for reducing console verbosity when running the full test suite.
```bash
./runtests.py -q
```
--------------------------------
### Implement XLSX Spreadsheet Export in Django REST Framework
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/renderers.md
Provides instructions for installing drf-excel and configuring it to render binary spreadsheet files. Includes a ViewSet example using XLSXFileMixin to manage file downloads and custom filenames.
```bash
pip install drf-excel
```
```python
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
'drf_excel.renderers.XLSXRenderer',
],
}
from rest_framework.viewsets import ReadOnlyModelViewSet
from drf_excel.mixins import XLSXFileMixin
from drf_excel.renderers import XLSXRenderer
from .models import MyExampleModel
from .serializers import MyExampleSerializer
class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):
queryset = MyExampleModel.objects.all()
serializer_class = MyExampleSerializer
renderer_classes = [XLSXRenderer]
filename = 'my_export.xlsx'
```
--------------------------------
### Create Custom Filter Backend in Django REST Framework
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/filtering.md
Implements a custom filter backend by extending BaseFilterBackend and overriding the filter_queryset method. This example restricts users to viewing only objects they created by filtering the queryset based on the request user.
```python
class IsOwnerFilterBackend(filters.BaseFilterBackend):
"""
Filter that only allows users to see their own objects.
"""
def filter_queryset(self, request, queryset, view):
return queryset.filter(owner=request.user)
```
--------------------------------
### Simple Equality-Based Filtering with filterset_fields
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/filtering.md
Shows how to implement basic equality-based filtering by setting the filterset_fields attribute on a ListAPIView. This automatically creates a FilterSet class for the specified fields and allows query parameter filtering. The example demonstrates filtering products by category and in_stock status.
```python
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = ['category', 'in_stock']
```
```http
http://example.com/api/products?category=clothing&in_stock=True
```
--------------------------------
### Create Django Superuser
Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/4-authentication-and-permissions.md
Command-line utility to create a superuser account for testing the API with authentication. Prompts for username, email, and password interactively.
```bash
python manage.py createsuperuser
```
--------------------------------
### Route Django TemplateView to serve ReDoc documentation
Source: https://github.com/encode/django-rest-framework/blob/main/docs/topics/documenting-your-api.md
Configures URL routing in Django to serve the ReDoc template with the OpenAPI schema. Uses TemplateView with extra_context to pass the schema URL to the template. Add this to your project's URL configuration file.
```python
from django.views.generic import TemplateView
urlpatterns = [
# ...
# Route TemplateView to serve the ReDoc template.
# * Provide `extra_context` with view name of `SchemaView`.
path(
"redoc/",
TemplateView.as_view(
template_name="redoc.html", extra_context={"schema_url": "openapi-schema"}
),
name="redoc",
),
]
```
--------------------------------
### Define Django REST Framework SearchFilter fields with related lookups
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/filtering.md
This example illustrates how to extend the `search_fields` attribute to include related model fields. It uses Django's double-underscore notation to perform lookups across ForeignKey or ManyToManyField relationships, enabling searching on attributes of related objects.
```python
search_fields = ['username', 'email', 'profile__profession']
```
--------------------------------
### Test for successful HTTP status code in Django REST framework
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/status-codes.md
This example shows how to use the `status.is_success()` helper function within a Django REST framework test case to verify if a response's status code indicates success (2xx range). It imports `status` and `APITestCase`, makes a GET request, and asserts the success status.
```python
from rest_framework import status
from rest_framework.test import APITestCase
class ExampleTestCase(APITestCase):
def test_url_root(self):
url = reverse('index')
response = self.client.get(url)
self.assertTrue(status.is_success(response.status_code))
```
--------------------------------
### Customize Django REST Framework SearchFilter behavior using field prefixes
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/filtering.md
This example shows how to modify the default search behavior for individual fields within `search_fields`. By prefixing field names with special characters (e.g., `=`, `^`, `$`), developers can specify exact matches, starts-with, or regex searches instead of the default 'contains' lookup.
```python
search_fields = ['=username', '=email']
```
--------------------------------
### Make Authenticated API Request with Basic Auth (HTTPie)
Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/4-authentication-and-permissions.md
This snippet shows how to successfully create a code snippet by providing basic authentication credentials. It uses the `httpie` command-line tool with the `-a` flag to include a username and password (e.g., 'admin:password123') in the POST request to the `/snippets/` endpoint, demonstrating a successful authenticated API call.
```bash
http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print(789)"
```
--------------------------------
### Override get_queryset in Django REST Framework ListAPIView
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/filtering.md
Demonstrates how to override the get_queryset() method in a generic ListAPIView to return a filtered queryset based on the authenticated user. This example shows filtering a many-to-many relationship (purchase_set) to return only products purchased by the current user. The view can be combined with additional filtering backends for enhanced functionality.
```python
class PurchasedProductsList(generics.ListAPIView):
"""
Return a list of all the products that the authenticated
user has ever purchased, with optional filtering.
"""
model = Product
serializer_class = ProductSerializer
filterset_class = ProductFilter
def get_queryset(self):
user = self.request.user
return user.purchase_set.all()
```
--------------------------------
### Build API documentation using API Star CLI
Source: https://github.com/encode/django-rest-framework/blob/main/docs/community/3.9-announcement.md
Command to generate static HTML documentation from an OpenAPI schema file using the API Star documentation builder.
```shell
apistar docs --path schema.json --format openapi
```
--------------------------------
### Initialize and Save Snippet Model Instances in Django Shell
Source: https://github.com/encode/django-rest-framework/blob/main/docs/tutorial/1-serialization.md
This Python console snippet demonstrates how to import necessary modules, create new `Snippet` model instances with sample code, and save them to the database. It sets up data for subsequent serialization examples.
```pycon
>>> from snippets.models import Snippet
>>> from snippets.serializers import SnippetSerializer
>>> from rest_framework.renderers import JSONRenderer
>>> from rest_framework.parsers import JSONParser
>>> snippet = Snippet(code='foo = "bar"\n')
>>> snippet.save()
>>> snippet = Snippet(code='print("hello, world")\n')
>>> snippet.save()
```
--------------------------------
### Cache APIView and ViewSet with method_decorator
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/caching.md
Demonstrates how to apply Django cache decorators to REST Framework ViewSets and APIView classes using method_decorator. Shows three examples: caching with cookie variation for 2 hours, caching with Authorization header variation, and basic page caching. The cache_page decorator caches GET and HEAD responses with status 200.
```python
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_cookie, vary_on_headers
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import viewsets
class UserViewSet(viewsets.ViewSet):
# With cookie: cache requested url for each user for 2 hours
@method_decorator(cache_page(60 * 60 * 2))
@method_decorator(vary_on_cookie)
def list(self, request, format=None):
content = {
"user_feed": request.user.get_user_feed(),
}
return Response(content)
class ProfileView(APIView):
# With auth: cache requested url for each user for 2 hours
@method_decorator(cache_page(60 * 60 * 2))
@method_decorator(vary_on_headers("Authorization"))
def get(self, request, format=None):
content = {
"user_feed": request.user.get_user_feed(),
}
return Response(content)
class PostView(APIView):
# Cache page for the requested url
@method_decorator(cache_page(60 * 60 * 2))
def get(self, request, format=None):
content = {
"title": "Post title",
"body": "Post content",
}
return Response(content)
```
--------------------------------
### Request.auth
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/requests.md
Returns any additional authentication context, such as a token instance, or `None` if not present or unauthenticated.
```APIDOC
## Property: .auth
### Description
Returns any additional authentication context, such as a token instance against which the request was authenticated. If the request is unauthenticated or no additional context is present, the default value is `None`. The exact behavior depends on the authentication policy in use.
### Type
Token instance, or `None`
### Usage Example
```python
# Access authentication token
if request.auth:
print(f"Auth token: {request.auth}")
```
### Notes
May raise `WrappedAttributeError` if an authenticator encounters an `AttributeError` internally.
```
--------------------------------
### Specify Allowed HTTP Methods for a Function-Based View using @api_view()
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/views.md
This example illustrates how to explicitly define the HTTP methods a function-based view will accept by passing a list to the `@api_view()` decorator. It prevents '405 Method Not Allowed' errors for unsupported methods and demonstrates handling different request types (GET, POST) within the same view. The `request.data` attribute is used to access POSTed data.
```python
@api_view(['GET', 'POST'])
def hello_world(request):
if request.method == 'POST':
return Response({"message": "Got some data!", "data": request.data})
return Response({"message": "Hello, world!"})
```
--------------------------------
### Define Custom Routable Actions in Django REST Framework ViewSets
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/viewsets.md
This comprehensive Python example illustrates how to add custom, routable actions to a Django REST Framework `ModelViewSet` using the `@action` decorator. It includes a `set_password` action (detail=True, POST method) for a specific user and a `recent_users` action (detail=False, GET by default) for the entire collection, demonstrating request data handling, serialization, pagination, and response generation within these custom methods.
```python
from django.contrib.auth.models import User
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from myapp.serializers import UserSerializer, PasswordSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
A viewset that provides the standard actions
"""
queryset = User.objects.all()
serializer_class = UserSerializer
@action(detail=True, methods=['post'])
def set_password(self, request, pk=None):
user = self.get_object()
serializer = PasswordSerializer(data=request.data)
if serializer.is_valid():
user.set_password(serializer.validated_data['password'])
user.save()
return Response({'status': 'password set'})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
@action(detail=False)
def recent_users(self, request):
recent_users = User.objects.all().order_by('-last_login')
page = self.paginate_queryset(recent_users)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(recent_users, many=True)
return Response(serializer.data)
```
--------------------------------
### Usage Examples for DecimalField Precision
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/fields.md
Practical examples of DecimalField configuration for different precision requirements, such as standard currency validation or high-precision scientific data.
```python
# Validate numbers up to 999 with 2 decimal places
serializers.DecimalField(max_digits=5, decimal_places=2)
# Validate numbers up to one billion with 10 decimal places
serializers.DecimalField(max_digits=19, decimal_places=10)
```
--------------------------------
### Content Negotiation Methods Comparison
Source: https://github.com/encode/django-rest-framework/blob/main/docs/api-guide/format-suffixes.md
Overview of different content negotiation approaches in REST APIs, including format suffixes, query parameters, and HTTP Accept headers. Explains the rationale and trade-offs between these methods.
```APIDOC
## Content Negotiation Methods
### Overview
Different approaches to specify desired response format in REST APIs.
### Method 1: Format Suffixes (File Extensions)
#### URL Pattern
```
http://example.com/api/users.json
http://example.com/api/users.html
```
#### Advantages
- Clear and explicit format specification
- Cacheable by standard HTTP caches
- Recognized as acceptable REST pattern
- Easy for clients to construct URLs
#### Implementation
```python
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
```
### Method 2: Query Parameters
#### URL Pattern
```
http://example.com/api/users/?format=json
http://example.com/api/users/?format=html
```
#### Advantages
- No URL path modification
- Flexible format selection
- Default method in Django REST Framework
- Used by browsable API
#### Configuration
```python
# settings.py
URL_FORMAT_OVERRIDE = 'format' # Default
# Set to None to disable
```
### Method 3: HTTP Accept Headers
#### Request Pattern
```
GET /api/users/
Accept: application/json
```
#### Characteristics
- Standard HTTP content negotiation
- No URL modification required
- Requires client to set headers
### Recommendation
Format suffixes and query parameters are both acceptable REST patterns. Choose based on API requirements and client preferences.
```
--------------------------------
### Run Specific Test Method
Source: https://github.com/encode/django-rest-framework/blob/main/docs/community/contributing.md
Execute a specific test method by providing the test case class name and method name separated by a dot, or use the shorter form with just the method name.
```bash
./runtests.py MyTestCase.test_this_method
./runtests.py test_this_method
```
--------------------------------
### Create Swagger UI HTML Template for Django
Source: https://github.com/encode/django-rest-framework/blob/main/docs/topics/documenting-your-api.md
A minimal HTML template used to render the Swagger UI interface. It loads assets from a CDN and initializes the SwaggerUIBundle with the schema URL and CSRF token support.
```html
Swagger
```