Django REST Framework CSV

3.0.2 · active · verified Sat Apr 11

djangorestframework-csv provides tools to integrate CSV rendering and parsing into Django REST Framework APIs. It enables DRF serializers to output data as CSV and allows DRF parsers to consume CSV data. The current version is 3.0.2, with releases tending to be driven by Django and DRF compatibility updates rather than a fixed cadence.

Warnings

Install

Imports

Quickstart

This example demonstrates how to integrate `CSVRenderer` into a Django REST Framework `APIView` to output a list of dictionary objects as CSV. When an endpoint using this renderer is accessed with a `.csv` format suffix (e.g., `/products.csv`), the response will be a CSV file. For very large datasets, consider using `CSVStreamingRenderer`.

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_csv.renderers import CSVRenderer

class ProductListView(APIView):
    renderer_classes = (CSVRenderer, )

    def get(self, request, *args, **kwargs):
        # In a real application, this would come from a database query
        # or a DRF serializer output.
        products = [
            {'id': 1, 'name': 'Laptop', 'price': 1200.00},
            {'id': 2, 'name': 'Mouse', 'price': 25.00},
            {'id': 3, 'name': 'Keyboard', 'price': 75.00}
        ]
        return Response(products)

# To integrate this, you would typically add it to a Django URLconf, e.g.:
# from django.urls import path
# urlpatterns = [
#     path('products.csv', ProductListView.as_view(), name='product-csv'),
# ]
# When accessing /products.csv, the API will return CSV data.

view raw JSON →