# Django Headless > A REST API for your Django models. # 🐍 Introduction Django Headless turns Django into the backend of a headless CMS. Decorate a model with `@expose()` and a [Django REST Framework](https://www.django-rest-framework.org/) API appears, with list, detail, create, update and delete routes, filtering, pagination and singletons. You write no serializers, viewsets or URL patterns. ```python # blog/models.py from django.db import models from headless import expose @expose() class Article(models.Model): title = models.CharField(max_length=200) body = models.TextField() published = models.BooleanField(default=False) ``` This decorator generates these routes: | Method | Route | Action | | -------- | ---------------------- | -------------- | | `GET` | `/api/blog.article` | List | | `POST` | `/api/blog.article` | Create | | `GET` | `/api/blog.article/1` | Retrieve | | `PUT` | `/api/blog.article/1` | Update | | `PATCH` | `/api/blog.article/1` | Partial update | | `DELETE` | `/api/blog.article/1` | Delete | :::note Protected by default Generated routes answer `403 Forbidden` to everyone but staff users, so an exposed model is never public by accident. To open the routes up, see [Permissions](https://djangoheadless.org/docs/permissions.md). ::: ## When to use it Use Django Headless when Django holds your content and the frontend lives elsewhere: a Next.js or Astro site, a static site build, a mobile app. The API is predictable for such a frontend: - **Routes per model**: one decorator per model, no URL patterns to maintain. - **Singletons**: site settings and other one-off objects as a single route. - **Filtering**: every lookup a field supports, from the query string. - **Lookup routes**: fetch an object by a unique field such as a slug. - **Stable lists**: ordered by primary key, with a pagination envelope that includes ready-to-fetch links. - **Clear errors**: invalid filters and options answer with the reason. If your editors also need an admin to manage that content, see [Django Content Studio](https://dwarsbit.github.io/django-content-studio/). For a production-ready Django stack with batteries included, see [Django Stack](https://djangostack.org). ## Next steps Follow the [installation guide](https://djangoheadless.org/docs/installation.md) to expose your first model. # 🚀 Installation This page sets up Django Headless in an existing Django project and exposes a first model. It takes four steps: install the package, add the apps, include the URLs and expose a model. ## Requirements - Python 3.12 or later - Django 5.2 or later, including 6.x - Django REST Framework 3.18 or later ## Set up the project 1. Install the package: ```bash pip install django-headless ``` 2. Add `rest_framework`, `headless` and `headless.rest` to `INSTALLED_APPS`: ```python # mysite/settings.py INSTALLED_APPS = [ # ... "django.contrib.staticfiles", "rest_framework", "headless", "headless.rest", ] ``` `headless` keeps track of the exposed models; `headless.rest` serves them as a REST API and builds its routes when the project starts. Without `headless.rest`, the API has no routes, and the [system check](https://djangoheadless.org/docs/checks.md#headlessw010) `headless.W010` warns about it. 3. Configure an authentication class, so requests can authenticate, and a pagination class if you want paginated lists. Add this to the same file: ```python # mysite/settings.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", ], "DEFAULT_PAGINATION_CLASS": "headless.rest.pagination.PageNumberPagination", "PAGE_SIZE": 25, } ``` 4. Include the API in your URL configuration: ```python # mysite/urls.py from django.urls import include, path urlpatterns = [ # ... path("api/", include("headless.rest.urls")), ] ``` :::note Staff users only Generated routes answer `403 Forbidden` to everyone but staff users, because `HEADLESS["DEFAULT_PERMISSION_CLASSES"]` defaults to `IsAdminUser`. For a public API, set it to `AllowAny`; see [Permissions](https://djangoheadless.org/docs/permissions.md). ::: ## Expose a model Decorate a model with `@expose()`: ```python # blog/models.py from django.db import models from headless import expose @expose() class Article(models.Model): title = models.CharField(max_length=200) body = models.TextField() published = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title ``` Run `python manage.py runserver`. The boot log lists the exposed models and the number of generated routes, and the article list is at `/api/blog.article`. Routes are built whenever the project starts: under `runserver`, a WSGI or ASGI server, management commands and tests. ## Related pages - [Exposing models](https://djangoheadless.org/docs/models.md) - [Settings reference](https://djangoheadless.org/docs/settings.md) # 🎯 Exposing models Expose a model with the `@expose()` decorator to give it generated routes. Use the decorator options to make a model a singleton, limit its fields, make it read-only or add lookup routes by a unique field. ```python # blog/models.py from django.db import models from headless import expose @expose() class Category(models.Model): name = models.CharField(max_length=100) @expose() class Article(models.Model): title = models.CharField(max_length=200) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name="articles") ``` Each exposed model gets routes at `/api/.`, such as `/api/blog.article`. To expose a model you cannot decorate, such as one from `django.contrib` or a third-party app, call `expose_model()`. It takes the model and the same options. This example needs `django.contrib.flatpages` in `INSTALLED_APPS`: ```python # blog/models.py from django.contrib.flatpages.models import FlatPage from headless import expose_model expose_model(FlatPage, read_only=True) ``` Django Headless builds the routes when the `headless.rest` app is ready, after every app's models module is imported. Call `expose_model()` in a models module, as above, or in the `ready()` method of an app listed before `headless.rest` in `INSTALLED_APPS`. A model exposed later has no routes; the [system check](https://djangoheadless.org/docs/checks.md#headlessw009) `headless.W009` reports it. Expose each model once: a second registration with other options replaces the first, and `headless.W008` warns about it. ## Options | Option | Type | Default | Description | | --------------- | ----------- | --------------------------- | ------------------------------------------------------------------------------------------------- | | `singleton` | `bool` | `False` | Expose the model as a single resource with `GET`, `PUT` and `PATCH`. See [Singletons](https://djangoheadless.org/docs/singletons.md). | | `search_fields` | `list[str]` | All serialized non-choice `CharField`s | Fields searched by DRF's `SearchFilter`. | | `fields` | `list[str]` | All fields | Serialize only these fields and model properties. | | `exclude` | `list[str]` | `None` | Serialize all fields except these. | | `read_only` | `bool` | `False` | Generate `GET` routes only. | | `lookup_fields` | `list[str]` | `None` | Unique fields to add a detail route for, at `by_/`. See [Lookup routes](#lookup-routes). | ## Field control By default, every model field is serialized. Use `fields` or `exclude` to keep data such as internal notes out of the API. The two options cannot be combined. ```python # blog/models.py from django.db import models from headless import expose @expose(exclude=["internal_notes"]) class Article(models.Model): title = models.CharField(max_length=200) internal_notes = models.TextField(blank=True) ``` Excluded fields are never serialized and are ignored on create and update. They cannot be filtered or expanded either, and they are not searched unless you name them in `search_fields`. A [system check](https://djangoheadless.org/docs/checks.md#headlessw006) warns when a field that looks like a credential, such as `password_hash` or `api_token`, is serialized without being named in `fields`. Exposing a user model requires a `fields` list to pass the checks ([`headless.W007`](https://djangoheadless.org/docs/checks.md#headlessw007)). `fields` can also name model properties, which are serialized as read-only fields. ## Read-only models Use `read_only=True` for content that the API serves but never changes: ```python # blog/models.py from django.db import models from headless import expose @expose(read_only=True) class Category(models.Model): name = models.CharField(max_length=100) ``` A read-only model gets the list and detail routes only. `POST`, `PUT`, `PATCH` and `DELETE` answer `405 Method Not Allowed`. ## Lookup routes A frontend often knows an object by a readable key, such as the slug in a page URL, rather than by its primary key. Use `lookup_fields` to add a detail route for each listed unique field: ```python # blog/models.py from django.db import models from headless import expose @expose(lookup_fields=["slug"]) class Article(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) body = models.TextField() ``` The article is then available by its slug as well as by its primary key: ```http GET /api/blog.article/by_slug/getting-started-with-django ``` ```json { "id": 1, "title": "Getting started with Django", "slug": "getting-started-with-django", "body": "..." } ``` A lookup route answers like the detail route: - An unknown value, or a value that does not fit the field's type (such as a malformed UUID), answers `404 Not Found`. - Values may contain dots, as in `by_slug/report.pdf`. URL-encode a value that contains a `/`. - The `expand` and `fields` query parameters work as on the detail route; see [Serializers](https://djangoheadless.org/docs/serializers.md). - Only `GET` is allowed. Create, update and delete through the detail route by primary key. Lookup routes are opt-in, so a unique field such as an email address is never exposed as a lookup by accident. A field qualifies when it has `unique=True` or a single-field `UniqueConstraint` without a `condition`. The primary key already has the detail route, and singletons cannot have lookup routes. :::note Permissions treat lookups as retrieves On a lookup route, DRF's `view.action` is `"retrieve"`, so permission classes that check the action apply as they do on the detail route. `view.lookup_by` holds the field of the lookup, such as `"slug"`, and is `None` on other routes. ::: ## Search fields `search_fields` sets the fields DRF's [`SearchFilter`](https://www.django-rest-framework.org/api-guide/filtering/#searchfilter) searches. The filter is not enabled by default; add it to `HEADLESS["DEFAULT_FILTER_BACKENDS"]` next to `LookupFilter`: ```python # mysite/settings.py HEADLESS = { "DEFAULT_FILTER_BACKENDS": [ "rest_framework.filters.SearchFilter", "headless.rest.filters.LookupFilter", ], } ``` ```python # blog/models.py from django.db import models from headless import expose @expose(search_fields=["title", "category__name"]) class Article(models.Model): title = models.CharField(max_length=200) category = models.ForeignKey("blog.Category", on_delete=models.PROTECT, related_name="articles") ``` Without `search_fields`, every serialized `CharField` without choices is searched. DRF's lookup prefixes (`^`, `=`, `@`, `$`) and relations (`category__name`) are supported. The rest of a name such as `category__name` is checked when the project starts, by the system check [`headless.E004`](https://djangoheadless.org/docs/checks.md#headlesse004). A field left out with `fields` or `exclude` can be searched by naming it in `search_fields`, for example keywords that should find an article without being served. Its values can be found out through the search, so the system check [`headless.W011`](https://djangoheadless.org/docs/checks.md#headlessw011) warns about it. Search with the `search` query parameter: ```http GET /api/blog.article?search=django ``` ## Database constraints The serializer validates a create or update before it is saved, but not every database constraint, such as a [`CheckConstraint`](https://docs.djangoproject.com/en/stable/ref/models/constraints/#checkconstraint). When a write violates such a constraint, the route answers `400 Bad Request` and saves nothing: ```json { "non_field_errors": ["The data conflicts with a database constraint."] } ``` The message does not name the constraint, so the database's details stay internal. To tell the frontend which field is wrong, add a validator to the model field as well. ## Validation `@expose()` and `expose_model()` raise `ImproperlyConfigured` when the model is defined if: - it decorates something that is not a Django model, or an abstract model; - `search_fields`, `fields`, `exclude` or `lookup_fields` is not a list or tuple, such as `fields=("title")`, which is a string because the comma is missing; - `search_fields`, `fields` or `exclude` name a field the model does not have; - `fields` and `exclude` are combined; - `lookup_fields` is not a list of unique fields of the model, names the primary key or is set on a singleton. ## Related pages - [Singletons](https://djangoheadless.org/docs/singletons.md) - [Serializers](https://djangoheadless.org/docs/serializers.md) # 💈 Singletons A singleton is an exposed model with exactly one instance, such as site settings. Its route has no primary key: the frontend reads it from one fixed URL. Expose a model as a singleton with `singleton=True`: ```python # blog/models.py from django.db import models from headless import expose @expose(singleton=True) class SiteSettings(models.Model): site_name = models.CharField(max_length=100) contact_email = models.EmailField() maintenance_mode = models.BooleanField(default=False) class Meta: verbose_name = "site settings" ``` The singleton gets one route with three methods: | Method | Route | Action | | ------- | ------------------------- | ------------------------------------ | | `GET` | `/api/blog.sitesettings` | Retrieve the singleton | | `PUT` | `/api/blog.sitesettings` | Update, creating it if it is missing | | `PATCH` | `/api/blog.sitesettings` | Partial update, creating it if it is missing | The first `PUT` or `PATCH` creates the singleton, so it takes every required field. After that, `PATCH` takes any subset of the fields. A singleton has no list or delete route. Create and edit it through the API, the Django admin or your own code. ## Creating on first write Until the singleton exists, `GET` answers `404 Not Found`. The first `PUT` or `PATCH` creates it and answers `201 Created`; later writes update it and answer `200 OK`. Concurrent first writes do not create duplicates: the request that loses the race updates the row the other request created. ## Read-only singletons Combine `singleton=True` with `read_only=True` to generate the `GET` method only. Use this for settings that editors change in the Django admin and the frontend only reads: ```python # blog/models.py from django.db import models from headless import expose @expose(singleton=True, read_only=True) class SiteSettings(models.Model): site_name = models.CharField(max_length=100) ``` ## Related pages - [Exposing models](https://djangoheadless.org/docs/models.md) # 🔍 Filtering `LookupFilter` filters list routes with query parameters named after Django's [field lookups](https://docs.djangoproject.com/en/stable/ref/models/querysets/#field-lookups), such as `?title__icontains=django`. The generated routes use it by default, through `HEADLESS["DEFAULT_FILTER_BACKENDS"]`. ```http GET /api/blog.article?published=true GET /api/blog.article?title__icontains=django GET /api/blog.article?created_at__gte=2026-01-01 GET /api/blog.article?category=2 ``` A parameter without a lookup matches exactly. Parameters read by the route's search, ordering and pagination, and `format`, `expand`, `fields` and `omit`, are not filters. Several parameters combine with AND: ```http GET /api/blog.article?published=true&created_at__year=2026 ``` To filter your own Django REST Framework views the same way, add `LookupFilter` to DRF's settings: ```python # mysite/settings.py REST_FRAMEWORK = { "DEFAULT_FILTER_BACKENDS": [ "headless.rest.filters.LookupFilter", ], } ``` ## Exposed fields Only fields the API serializes can be filtered. A field left out with `fields` or `exclude` answers `400 Bad Request`, the same as a field that does not exist, so its values cannot be guessed through lookups such as `__startswith`. Lookups can follow a relation to another exposed model and filter on its serialized fields. A relation to a model that is not exposed can only be filtered by primary key: ```http GET /api/blog.article?category__name__icontains=tutorials GET /api/blog.article?category__in=2,3 ``` `pk` stands for the primary key, as in Django: `?pk__in=1,2,3` on a list route, or `?category__pk=2` across a relation. ## Exclusions Start a parameter with `~` to exclude the matches instead: ```http GET /api/blog.article?~category=3 ``` Change the symbol with `HEADLESS["FILTER_EXCLUSION_SYMBOL"]`; see the [settings reference](https://djangoheadless.org/docs/settings.md#filter-settings). ## Multiple values The `in` and `range` lookups take comma-separated values: ```http GET /api/blog.article?id__in=1,2,3 GET /api/blog.article?created_at__range=2026-01-01,2026-06-30 ``` Repeating the parameter works as well: `?id__in=1&id__in=2`. Only `in` and `range` split on commas. Other lookups take the value as sent, so `?title=Hello, world` matches the title `Hello, world`. Values of `in` and `range` cannot contain a comma; filter such values with a single-value lookup such as `exact`. ## Type casting `LookupFilter` casts each value to the type of its field: - **Booleans**: `true`, `1` and `on` are true; `false`, `0` and `off` are false. - **Null values**: on a nullable boolean field, `null`, `none` and `empty` match `None`. The `isnull` lookup takes a boolean. - **Numbers**: integers, decimals and floats are parsed for their fields. - **Text**: kept as sent, so case-sensitive lookups such as `exact` match the case. Boolean and null values are case-insensitive. Change the recognized values with the `FILTER_*` settings. ## Disallowed lookups The `regex` and `iregex` lookups are disallowed and answer `400 Bad Request`. A costly regular expression can keep the database busy for a long time, and an invalid one fails in the database. Use `contains`, `startswith` or `endswith` instead, or change the list with `HEADLESS["FILTER_DISALLOWED_LOOKUPS"]`: ```python # mysite/settings.py HEADLESS = { "FILTER_DISALLOWED_LOOKUPS": ["regex", "iregex", "search"], } ``` ## Errors An unknown field, an unsupported lookup or a value that cannot be cast answers `400 Bad Request` with the reason: ```json { "detail": "Field 'titel' does not exist" } ``` The reason names the query parameter that failed, such as `Unsupported lookup in 'title__startwith'.` or `Invalid value for 'created_at__gte'`, followed by the expected format when Django provides one. The `range` lookup takes exactly two values. ## Related pages - [Pagination](https://djangoheadless.org/docs/pagination.md) - [Settings reference](https://djangoheadless.org/docs/settings.md) # 📃 Pagination `PageNumberPagination` splits list routes into pages and wraps them in an envelope with the total count and links to the next and previous page. Enable it for the generated routes in `HEADLESS`: ```python # mysite/settings.py HEADLESS = { "DEFAULT_PAGINATION_CLASS": "headless.rest.pagination.PageNumberPagination", "PAGE_SIZE": 25, } ``` When these two settings are not in `HEADLESS`, the generated routes use the ones in `REST_FRAMEWORK`. Without a pagination class and page size, a list route returns every object; `python manage.py check --deploy` warns about that (see [System checks](https://djangoheadless.org/docs/checks.md#headlessw004)). Request a page with the `page` query parameter. The `limit` query parameter overrides `PAGE_SIZE` for one request: ```http GET /api/blog.article?page=2&limit=10 ``` ## The envelope A list route answers with a `pagination` object and the items in `data`: ```json { "pagination": { "count": 42, "pages": 2, "current": 1, "limit": 25, "links": { "self": "https://example.org/api/blog.article?limit=25", "next": "https://example.org/api/blog.article?limit=25&page=2", "previous": null } }, "data": [ { "id": 1, "title": "Getting started with Django", "...": "..." } ] } ``` `count` is the number of items in the whole list, `pages` the number of pages, `current` the page number and `limit` the number of items per page, after the `limit` query parameter and the [maximum page size](#page-size) are applied. `links.next` and `links.previous` are complete URLs, so the frontend can page through a list without building URLs itself. On the first and last page, the missing link is `null`. ## Page size A client can request up to `HEADLESS["MAX_PAGE_SIZE"]` items per page with `limit`; larger values are lowered to it. The default maximum is `100`. Without a maximum, one request can return a whole table and keep the database and the server busy. ```python # mysite/settings.py HEADLESS = { "DEFAULT_PAGINATION_CLASS": "headless.rest.pagination.PageNumberPagination", "PAGE_SIZE": 25, "MAX_PAGE_SIZE": 50, } ``` On your own views, `PageNumberPagination` uses a maximum of `100`. Change it with a subclass that sets `max_page_size`. ## Ordering Generated list routes are ordered by primary key, so a page holds the same items on every request. ## Related pages - [Filtering](https://djangoheadless.org/docs/filtering.md) - [Settings reference](https://djangoheadless.org/docs/settings.md#drf-overrides) # 🔑 Authentication Generated routes only answer staff users by default (see [Permissions](https://djangoheadless.org/docs/permissions.md)), so a client gets access by authenticating. Django Headless works with any Django REST Framework [authentication class](https://www.django-rest-framework.org/api-guide/authentication/), and ships `SecretKeyAuthentication` for clients that run without a user, such as a static site build. ## Secret key authentication To let a client authenticate with a shared secret key: 1. Set the key and add `SecretKeyAuthentication` to the generated routes: ```python # mysite/settings.py HEADLESS = { "AUTH_SECRET_KEY": "your-secret-key", "DEFAULT_AUTHENTICATION_CLASSES": [ "headless.rest.authentication.SecretKeyAuthentication", ], } ``` 2. Send the key in the `X-Secret-Key` header with each request: ```bash curl -H "X-Secret-Key: your-secret-key" https://example.org/api/blog.article ``` Read the key from an environment variable rather than writing it in `settings.py`. Change the header name with `HEADLESS["AUTH_SECRET_KEY_HEADER"]`. A request with a wrong key, or a key with characters outside ASCII, answers `401 Unauthorized`. A request without the header is passed on to the next authentication class, so you can combine `SecretKeyAuthentication` with session or token authentication. To use `SecretKeyAuthentication` on your own views as well, add it to `REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"]` instead. :::warning Set a key Without `AUTH_SECRET_KEY` or `AUTH_READ_ONLY_SECRET_KEY`, every request to a route that uses `SecretKeyAuthentication` fails with an error. The [system check](https://djangoheadless.org/docs/checks.md#headlesse001) `headless.E001` reports a missing key and stops `runserver` until you set one. ::: A request authenticated with the secret key is not tied to a user account. It counts as a staff user, so it passes the default `IsAdminUser` permission and can read and change content on the generated routes. ### Read-only key A frontend that only reads content does not need a key that can change it. Give it a read-only key with `HEADLESS["AUTH_READ_ONLY_SECRET_KEY"]`. This key allows `GET`, `HEAD` and `OPTIONS` requests; other methods answer `403 Forbidden`. ```python # mysite/settings.py HEADLESS = { "AUTH_SECRET_KEY": "your-secret-key", "AUTH_READ_ONLY_SECRET_KEY": "your-read-only-key", "DEFAULT_AUTHENTICATION_CLASSES": [ "headless.rest.authentication.SecretKeyAuthentication", ], } ``` Both keys are sent in the same header. Set either key or both; they must be different. `SecretKeyAuthentication` enforces the read-only restriction itself, so it holds on every view that uses it, whatever the permission classes. In your own permission classes, `request.auth.read_only` tells whether a request used the read-only key. ## Other authentication classes Configure DRF's own classes the same way, in `HEADLESS["DEFAULT_AUTHENTICATION_CLASSES"]` for the generated routes only, or in `REST_FRAMEWORK` for your whole project: ```python # mysite/settings.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", ], } ``` When `HEADLESS["DEFAULT_AUTHENTICATION_CLASSES"]` is not set, the generated routes use the classes in `REST_FRAMEWORK`. ## Related pages - [Permissions](https://djangoheadless.org/docs/permissions.md) - [Settings reference](https://djangoheadless.org/docs/settings.md#auth_secret_key-auth_read_only_secret_key-and-auth_secret_key_header) # 🧩 Serializers Each exposed model is serialized with a `ModelSerializer` that includes all fields, minus those left out with `fields` or `exclude` (see [Exposing models](https://djangoheadless.org/docs/models.md#field-control)). To expand relations and serialize model properties, switch to `FlexibleSerializer`: ```python # mysite/settings.py HEADLESS = { "DEFAULT_SERIALIZER_CLASS": "headless.rest.serializers.FlexibleSerializer", } ``` `HEADLESS["DEFAULT_SERIALIZER_CLASS"]` sets the base class for the serializers of all exposed models. ## FlexibleSerializer `FlexibleSerializer` builds on [drf-flex-fields](https://github.com/rsinger86/drf-flex-fields) and adds two things to the default serializer: - **Model properties** are serialized as read-only fields. Properties whose name starts with `_` are left out. - **Relations to other exposed models** can be expanded inline with the `expand` query parameter. ```python # blog/models.py from django.db import models from headless import expose @expose() class Category(models.Model): name = models.CharField(max_length=100) @expose() class Article(models.Model): title = models.CharField(max_length=200) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name="articles") @property def word_count(self): return len(self.body.split()) ``` Every article now includes `word_count`. ## Expanding relations By default, a relation is serialized as the primary key of the related object. Name the relation in `expand` to include the related object instead: ```http GET /api/blog.article/1?expand=category GET /api/blog.category/1?expand=articles ``` ```json { "id": 1, "title": "Getting started with Django", "category": { "id": 2, "name": "Tutorials" }, "word_count": 1250, "...": "..." } ``` Forward relations are expanded by field name (`category`). Reverse relations are expanded by the name they have on an object: their `related_name` (`articles`), or `_set` without one, such as `review_set` for the reviews of an article. Only relations to exposed models can be expanded; other relations stay primary keys. An expanded object is serialized with `HEADLESS["DEFAULT_SERIALIZER_CLASS"]`, so it expands further only when that is `FlexibleSerializer`. Paths are limited to two relations, such as `?expand=category.articles`, and a longer path answers `400 Bad Request`. Change the limit with [`HEADLESS["MAX_EXPANSION_DEPTH"]`](https://djangoheadless.org/docs/settings.md#max_expansion_depth). An expanded object follows the `fields` and `exclude` options of its own model. Relations and properties left out with `fields` or `exclude` are not serialized and cannot be expanded. ## Queries The number of queries of a route does not grow with the number of objects in a response. An expanded foreign key or one-to-one relation is loaded together with the object, and every other expanded relation takes one query. Many-to-many fields (and reverse relations that are serialized) take one query each as well, whether or not they are expanded, because every object in a list lists the primary keys of its related objects. Relations that `?fields=` or `?omit=` leave out of the response are not loaded, so `?fields=title,slug` takes no queries for relations at all. A model property that queries the database runs once per object. Keep such properties cheap, or leave them out of the API with `exclude`. ## Related pages - [Exposing models](https://djangoheadless.org/docs/models.md) - [Settings reference](https://djangoheadless.org/docs/settings.md#default_serializer_class) # 🛡️ Permissions Generated routes only answer staff users by default: `HEADLESS["DEFAULT_PERMISSION_CLASSES"]` defaults to DRF's `IsAdminUser`. A newly exposed model is not public until you open its routes up in your settings, and users without staff status cannot change content. This matters because DRF enables session and basic authentication when `REST_FRAMEWORK` sets no authentication classes, so every user account of your site can authenticate. Requests with a valid [secret key](https://djangoheadless.org/docs/authentication.md#secret-key-authentication) count as staff. The boot log shows the authentication and permission classes the generated routes use. ## Public content For a public headless CMS, allow every request on the generated routes: ```python # mysite/settings.py HEADLESS = { "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.AllowAny"], } ``` `AllowAny` also allows writes; the [system check](https://djangoheadless.org/docs/checks.md#headlessw002) `headless.W002` warns about it. To serve content publicly and accept changes only from authenticated clients, use `IsAuthenticatedOrReadOnly`, or mark models that should never change through the API with `read_only=True` (see [Exposing models](https://djangoheadless.org/docs/models.md#read-only-models)). ```python # mysite/settings.py HEADLESS = { "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticatedOrReadOnly"], } ``` ## Generated routes and your own views `HEADLESS["DEFAULT_PERMISSION_CLASSES"]` applies to the generated routes only. It replaces `REST_FRAMEWORK["DEFAULT_PERMISSION_CLASSES"]` there and leaves your own views untouched. The generated routes do not use the `REST_FRAMEWORK` permission classes; to use the same classes on both, set them in both settings. ```python # mysite/settings.py # Your own views are for staff users only; the generated routes are open to every authenticated user. REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAdminUser"], } HEADLESS = { "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"], } ``` Both settings take dotted paths and classes. :::warning Configure authentication Permission classes only grant access to clients that can authenticate. Configure an authentication class in `REST_FRAMEWORK` or `HEADLESS["DEFAULT_AUTHENTICATION_CLASSES"]`; see [Authentication](https://djangoheadless.org/docs/authentication.md). ::: Other DRF settings, such as renderers, parsers and pagination, can be set for the generated routes in the same way; see [DRF overrides](https://djangoheadless.org/docs/settings.md#drf-overrides). ## Lookup routes On [lookup routes](https://djangoheadless.org/docs/models.md#lookup-routes), DRF's `view.action` is `"retrieve"`. A permission class that checks the action treats `GET /api/blog.article/by_slug/getting-started-with-django` like `GET /api/blog.article/1`. ## Related pages - [Authentication](https://djangoheadless.org/docs/authentication.md) - [Settings reference](https://djangoheadless.org/docs/settings.md) # 📘 OpenAPI schema Django Headless can describe the generated routes in an [OpenAPI](https://spec.openapis.org/oas/v3.0.3) 3.0 schema. Typed clients and API tools read it: a frontend generates its TypeScript types from the schema instead of writing them by hand, and the types follow the models. ## Enabling the schema The schema needs the `uritemplate` and `inflection` packages, and PyYAML for YAML output. Install them with the `schema` extra: ```bash pip install "django-headless[schema]" ``` Then enable the schema route with `HEADLESS["SCHEMA"]`: ```python # mysite/settings.py HEADLESS = { "SCHEMA": True, "SCHEMA_TITLE": "Blog API", } ``` The schema is served next to the generated routes, at `/api/schema`: ```http GET /api/schema ``` The default format is JSON. Add `?format=openapi` for YAML, which needs PyYAML. A request with an `Accept` header gets the format it asks for. `python manage.py check` reports an error (`headless.E003`) when `SCHEMA` is enabled and the packages are missing; see [System checks](https://djangoheadless.org/docs/checks.md#headlesse003). ## What the schema describes The schema covers the generated routes only, not the other views of your project. For each route it lists: - **Operations** with unique IDs such as `listBlogArticles` and `retrieveBlogArticle`, a description and a tag per model. - **Components** named after the model, such as `BlogArticle` for `blog.Article`, with the types of its fields. Model properties are read-only fields, typed after their return annotation, such as `def word_count(self) -> int`; a property without one allows any value. - **Pagination**: the `page` and `limit` query parameters, and the `pagination` and `data` envelope of the [list response](https://djangoheadless.org/docs/pagination.md#the-envelope). - **Filters**: a query parameter for each filterable field of a list route, typed from the model field, with the choices of a field that has them. [Lookups](https://djangoheadless.org/docs/filtering.md) such as `views__gte` and exclusions with `~` apply to every one of them and are mentioned in each description. - **Expansion**: the `expand`, `fields` and `omit` query parameters of [`FlexibleSerializer`](https://djangoheadless.org/docs/serializers.md), with the names of the expandable relations. - **Lookup routes** such as `/api/blog.article/by_slug/{value}`, with the type of the field as the type of `value`. - **Authentication**: the secret key header of [`SecretKeyAuthentication`](https://djangoheadless.org/docs/authentication.md), and the token, basic and session authentication of Django REST Framework. Other authentication classes are not described. ## Access to the schema The schema route requires what the generated routes require, which is a staff user by default; see [Permissions](https://djangoheadless.org/docs/permissions.md). It lists the operations the requester may perform: with `IsAuthenticatedOrReadOnly`, an anonymous request sees the read operations and not the write operations, and so does a request with the read-only secret key. Authenticate the request for the schema like any other request, for example with the `X-Secret-Key` header when you generate types in a build step. ## Settings | Setting | Default | Description | | --------------------------- | -------- | ---------------------------------------------- | | `SCHEMA` | `False` | Whether the schema route exists. | | `SCHEMA_TITLE` | `"API"` | The title of the schema. | | `SCHEMA_DESCRIPTION` | `""` | The description of the schema. | | `SCHEMA_VERSION` | `"1.0.0"` | The version of your API, not of Django Headless. | ## Generating a file To commit the schema or generate it in a build step, use Django REST Framework's `generateschema` command with the Django Headless generator. It needs no `SCHEMA` setting and no running server: ```bash python manage.py generateschema \ --generator_class headless.rest.schema.SchemaGenerator \ --format openapi-json \ --file openapi.json ``` A generated file describes every operation, whatever the permissions of the routes. ## Extensions The schema adds two [extensions](https://spec.openapis.org/oas/v3.0.3#specification-extensions) for typed clients. Tools that do not know them ignore them. - **`x-filter`** is `true` on each filter parameter of a list route. - **`x-expandable`** on the `expand` parameter maps each expandable relation to the component of its model, and tells whether it expands to a list: ```json { "category": { "component": "BlogCategory", "many": false }, "review_set": { "component": "BlogReview", "many": true } } ``` The [TypeScript client](https://djangoheadless.org/docs/client.md) reads them to type filters and expanded relations. ## Limitations - **Expanded relations** are described as primary keys, as they are without `?expand=`. A response with `?expand=` has the related object in their place. The [TypeScript client](https://djangoheadless.org/docs/client.md) types the expanded objects. - **Custom schema classes**: when `REST_FRAMEWORK["DEFAULT_SCHEMA_CLASS"]` is not Django REST Framework's `AutoSchema`, for example with [drf-spectacular](https://drf-spectacular.readthedocs.io/), the generated routes keep your class and the schema route of Django Headless does not describe them. Use the schema view of that package instead. ## Related pages - [TypeScript client](https://djangoheadless.org/docs/client.md) - [Filtering](https://djangoheadless.org/docs/filtering.md) - [Pagination](https://djangoheadless.org/docs/pagination.md) - [Settings reference](https://djangoheadless.org/docs/settings.md#schema-settings) # 🔌 TypeScript client The `@django-headless/client` npm package is a client for the API, written in TypeScript. It requests the generated routes from the frontend or a static site build, and generates the types of your exposed models from the [OpenAPI schema](https://djangoheadless.org/docs/schema.md), so a typo in a field, filter or relation fails the type check instead of the request. The client uses the global `fetch` and has no dependencies. It runs in Node.js 18 and later, in browsers and in edge runtimes. ## Installation ```bash npm install @django-headless/client ``` ## Requesting the API Create a client with the URL the API is included at, and request the routes of a model by its label: ```ts // src/api.ts import { DjangoRestClient } from "@django-headless/client"; export const api = new DjangoRestClient({ baseUrl: "https://example.org/api", secretKey: process.env.HEADLESS_SECRET_KEY, }); const { pagination, data } = await api.model("blog.article").list({ filters: { published: true }, }); ``` `secretKey` is sent in the `X-Secret-Key` header of [`SecretKeyAuthentication`](https://djangoheadless.org/docs/authentication.md). Without the generated types, every label is accepted and objects have the type `{ [key: string]: unknown }`. ## Generating the types The client types the routes from the OpenAPI schema of the API. To generate the types: 1. Enable the schema route; see [Enabling the schema](https://djangoheadless.org/docs/schema.md#enabling-the-schema). 2. Generate the types into a file of the frontend: ```bash npx headless generate --url https://example.org/api/schema --out src/headless.ts ``` The command reads the secret key of the schema route from the `DJANGO_HEADLESS_SECRET_KEY` environment variable, or from `--secret-key`. Send other headers with `--header "Authorization: Token your-token"`. 3. Pass the `Models` type of the file to the client: ```ts // src/api.ts import { DjangoRestClient } from "@django-headless/client"; import type { Models } from "./headless"; export const api = new DjangoRestClient({ baseUrl: "https://example.org/api", secretKey: process.env.HEADLESS_SECRET_KEY, }); ``` Without a schema route, generate the types from a schema file of `generateschema`; see [Generating a file](https://djangoheadless.org/docs/schema.md#generating-a-file): ```bash npx headless generate --file openapi.json --out src/headless.ts ``` The file has an interface per model, such as `BlogArticle` for `blog.Article`, and a `BlogArticleInput` for the body of a create or update request. Run the command again when the exposed models change, for example in a script of the frontend: ```json { "scripts": { "generate": "headless generate --url https://example.org/api/schema --out src/headless.ts" } } ``` The schema lists the operations the requester may perform. Generate the types with a key that may write, or the client types every model as read only. ## Models `api.model(label)` has a method per route: ```ts const articles = api.model("blog.article"); await articles.list({ filters: { published: true }, page: 2 }); await articles.retrieve(1); await articles.retrieveBy("slug", "getting-started-with-django"); await articles.create({ title: "Getting started with Django", category: 2 }); await articles.update(1, { title: "Getting started with Django", category: 2 }); await articles.partialUpdate(1, { title: "Getting started" }); await articles.destroy(1); ``` - `list()` answers the [pagination envelope](https://djangoheadless.org/docs/pagination.md#the-envelope), with the objects in `data`. Without a pagination class, it answers the list of objects. - `retrieveBy()` requests a [lookup route](https://djangoheadless.org/docs/models.md#lookup-routes) such as `/api/blog.article/by_slug/`. The generated types only accept the fields of the lookup routes. - `create()`, `update()` and `partialUpdate()` send JSON. Pass a `FormData` instead to upload files. - A read-only model has the read methods only. To request every page, iterate over the objects or collect them with `all()`. Both request one page at a time: ```ts for await (const article of api.model("blog.article").iterate({ filters: { published: true } })) { console.log(article.title); } const articles = await api.model("blog.article").all({ limit: 100 }); ``` ## Singletons `api.singleton(label)` requests the route of a [singleton](https://djangoheadless.org/docs/singletons.md): ```ts const settings = api.singleton("blog.sitesettings"); await settings.retrieve(); await settings.partialUpdate({ site_name: "The Django blog" }); ``` ## Filtering and searching `filters` takes the [lookups](https://djangoheadless.org/docs/filtering.md) of the list route, and `exclude` the [exclusions](https://djangoheadless.org/docs/filtering.md#exclusions): ```ts await api.model("blog.article").list({ filters: { title__icontains: "django", created_at__gte: new Date("2026-01-01"), category__in: [2, 3], }, exclude: { category: 4 }, search: "getting started", ordering: ["-created_at"], limit: 20, }); ``` ```http GET /api/blog.article?title__icontains=django&created_at__gte=2026-01-01T00:00:00.000Z&category__in=2,3&~category=4&search=getting+started&ordering=-created_at&limit=20 ``` Lists are sent as comma-separated values, a `Date` as an ISO 8601 string and `null` as `null`. A `Date` filters a `DateTimeField`; filter a `DateField` with a string such as `"2026-01-15"`. Only nullable boolean fields read `null`; use `isnull` for other fields, as in `category__isnull: true`. With the generated types, the value of each field and lookup is type-checked. Other lookups, such as `created_at__year`, and lookups across relations, such as `category__name__icontains`, are accepted without type checks on their values. `search` and `ordering` need a search and an ordering filter backend; see [DRF overrides](https://djangoheadless.org/docs/settings.md#drf-overrides). ## Expanding relations With [`FlexibleSerializer`](https://djangoheadless.org/docs/serializers.md), `expand` includes related objects instead of primary keys, and `fields` and `omit` select the fields. The generated types follow them: the type of the response has the expanded objects and only the selected fields. ```ts const article = await api.model("blog.article").retrieve(1, { expand: ["category", "review_set"], omit: ["body"], }); article.category.name; // a BlogCategory, not a primary key article.review_set[0].rating; // a list of BlogReview ``` Paths such as `category.articles` expand deeper. `fields` and `omit` type the top-level fields only: `fields: ["category.name"]` keeps all fields in the type of `category`. ## Options | Option | Default | Description | | ----------------- | ---------------- | --------------------------------------------------------------------------------------------------------- | | `baseUrl` | required | The URL the API is included at. | | `secretKey` | none | The secret key of `SecretKeyAuthentication`. | | `secretKeyHeader` | `"X-Secret-Key"` | The header of the secret key, as in `HEADLESS["AUTH_SECRET_KEY_HEADER"]`. | | `headers` | none | Headers of every request, or a function that returns them, for example with a token. | | `fetch` | global `fetch` | The `fetch` function to use. | | `init` | none | Other options for `fetch` of every request, such as `cache` or `credentials`. | | `exclusionSymbol` | `"~"` | The symbol of exclusions, as in `HEADLESS["FILTER_EXCLUSION_SYMBOL"]`. | | `searchParam` | `"search"` | The query parameter of `search`, as in `HEADLESS["SEARCH_PARAM"]`. | | `orderingParam` | `"ordering"` | The query parameter of `ordering`, as in `HEADLESS["ORDERING_PARAM"]`. | Every method takes the options of one request as its last argument: `headers`, `signal` to cancel the request with an `AbortController`, and `init` for other options of `fetch`. In Next.js, pass the cache options of a request in `init`: ```ts const { data } = await api.model("blog.article").list({ filters: { published: true } }, { init: { next: { revalidate: 60 } } }); ``` ## Errors A response with an error status throws a `DjangoRestError`, with the status and the parsed body: ```ts import { DjangoRestError } from "@django-headless/client"; try { await api.model("blog.article").retrieveBy("slug", "missing"); } catch (error) { if (error instanceof DjangoRestError && error.status === 404) { // Show the not found page } throw error; } ``` `body` holds the JSON of the response, such as `{ "detail": "Not found." }`, or the validation errors per field of a `400 Bad Request`. ## Other routes `api.request()` sends a request to any path of the API and parses the JSON response: ```ts const result = await api.request("GET", "blog.article/1"); ``` ## Related pages - [OpenAPI schema](https://djangoheadless.org/docs/schema.md) - [Authentication](https://djangoheadless.org/docs/authentication.md) - [Filtering](https://djangoheadless.org/docs/filtering.md) - [Serializers](https://djangoheadless.org/docs/serializers.md) # ⚙️ Settings reference All Django Headless settings live in the `HEADLESS` dictionary in your Django settings. Every key is optional, and a key that is not a setting is reported by the [system check](https://djangoheadless.org/docs/checks.md#headlessw005) `headless.W005`. This is the full dictionary with the defaults: ```python # mysite/settings.py HEADLESS = { "BOOT_LOG": None, "VERSION_CHECK": True, "AUTH_SECRET_KEY": None, "AUTH_READ_ONLY_SECRET_KEY": None, "AUTH_SECRET_KEY_HEADER": "X-Secret-Key", "DEFAULT_RENDERER_CLASSES": None, "DEFAULT_PARSER_CLASSES": None, "DEFAULT_AUTHENTICATION_CLASSES": None, "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAdminUser"], "DEFAULT_FILTER_BACKENDS": ["headless.rest.filters.LookupFilter"], "DEFAULT_PAGINATION_CLASS": None, "PAGE_SIZE": None, "MAX_PAGE_SIZE": 100, "MAX_EXPANSION_DEPTH": 2, "SEARCH_PARAM": None, "ORDERING_PARAM": None, "SCHEMA": False, "SCHEMA_TITLE": "API", "SCHEMA_DESCRIPTION": "", "SCHEMA_VERSION": "1.0.0", "DEFAULT_SERIALIZER_CLASS": "rest_framework.serializers.ModelSerializer", "FILTER_EXCLUSION_SYMBOL": "~", "FILTER_TRUE_VALUES": ["true", "1", "on"], "FILTER_FALSE_VALUES": ["false", "0", "off"], "FILTER_NULL_VALUES": ["null", "none", "empty"], "FILTER_DISALLOWED_LOOKUPS": ["regex", "iregex"], "NON_FILTER_FIELDS": [ "search", "limit", "page", "fields", "omit", "expand", "ordering", ], } ``` ## `BOOT_LOG` Whether the boot log is shown when the project starts. The boot log lists the exposed models, the number of generated routes, and the authentication and permission classes in use. - `None` (default): shown under `runserver` and the WSGI and ASGI servers Gunicorn, Uvicorn, Daphne, Hypercorn, uWSGI, Waitress, Granian and mod_wsgi. Not shown for other management commands, tests, task workers such as Celery, or scripts. With autoreload, `runserver` shows it once, in the process that serves requests. - `True`: always shown. Use it for a server that is not in the list above. - `False`: never shown. ## `VERSION_CHECK` Whether the boot log checks PyPI for a newer version of Django Headless. The check runs only when the boot log is shown, waits at most five seconds for PyPI and caches the answer for a day (a failed check for five minutes) in your default cache. When PyPI or the cache cannot be reached, the boot log shows the installed version and the project starts as usual. Set it to `False` to never contact PyPI, for example on servers without outgoing internet access. ## DRF overrides These settings take the same values as their Django REST Framework [counterparts](https://www.django-rest-framework.org/api-guide/settings/) in `REST_FRAMEWORK`. They apply to the generated routes only and leave your own views untouched. | Setting | Default | | -------------------------------- | ------------------------------------------------ | | `DEFAULT_RENDERER_CLASSES` | `None`: use `REST_FRAMEWORK` | | `DEFAULT_PARSER_CLASSES` | `None`: use `REST_FRAMEWORK` | | `DEFAULT_AUTHENTICATION_CLASSES` | `None`: use `REST_FRAMEWORK` | | `DEFAULT_PERMISSION_CLASSES` | `["rest_framework.permissions.IsAdminUser"]` | | `DEFAULT_FILTER_BACKENDS` | `["headless.rest.filters.LookupFilter"]` | | `DEFAULT_PAGINATION_CLASS` | `None`: use `REST_FRAMEWORK` | | `PAGE_SIZE` | `None`: use `REST_FRAMEWORK` | | `SEARCH_PARAM` | `None`: use DRF's default, `search` | | `ORDERING_PARAM` | `None`: use DRF's default, `ordering` | A setting set to `None` falls back to `REST_FRAMEWORK`. `DEFAULT_PERMISSION_CLASSES` and `DEFAULT_FILTER_BACKENDS` have their own defaults and never fall back: the generated routes require a staff user and support [filtering](https://djangoheadless.org/docs/filtering.md) whatever `REST_FRAMEWORK` says. Set them under `HEADLESS` to change them. ```python # mysite/settings.py HEADLESS = { "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.AllowAny"], "DEFAULT_PAGINATION_CLASS": "headless.rest.pagination.PageNumberPagination", "PAGE_SIZE": 25, "SEARCH_PARAM": "q", } ``` All these settings take dotted paths and classes. `PAGE_SIZE` has no effect without a pagination class; set `DEFAULT_PAGINATION_CLASS` here or in `REST_FRAMEWORK`. `SEARCH_PARAM` and `ORDERING_PARAM` apply to DRF's `SearchFilter` and `OrderingFilter` when they are in `DEFAULT_FILTER_BACKENDS`. Subclasses of those filters and other filter backends keep their own parameter names. ## `MAX_PAGE_SIZE` The largest page size a client can request on the generated routes, with `?limit=` for `PageNumberPagination` and `LimitOffsetPagination`. Larger values are lowered to it. The default is `100`; `None` removes the maximum, which lets a single request return a whole table. It replaces the maximum of the pagination class (`max_page_size`, or `max_limit` for `LimitOffsetPagination`) on the generated routes. See [Pagination](https://djangoheadless.org/docs/pagination.md#page-size). ## `MAX_EXPANSION_DEPTH` The deepest relation path a client can [expand](https://djangoheadless.org/docs/serializers.md#expanding-relations) with `FlexibleSerializer`, counted in relations: `?expand=category` has depth 1, `?expand=category.articles` depth 2. Deeper paths answer `400 Bad Request`. The default is `2`; `None` allows any depth. The `MAXIMUM_EXPANSION_DEPTH` setting of drf-flex-fields takes precedence when set. ## `AUTH_SECRET_KEY`, `AUTH_READ_ONLY_SECRET_KEY` and `AUTH_SECRET_KEY_HEADER` The full access key, the [read-only key](https://djangoheadless.org/docs/authentication.md#read-only-key) and the header name for [`SecretKeyAuthentication`](https://djangoheadless.org/docs/authentication.md). The header defaults to `X-Secret-Key`. ## `DEFAULT_SERIALIZER_CLASS` The base class for the serializers of exposed models. Set it to `headless.rest.serializers.FlexibleSerializer` to [expand relations and serialize model properties](https://djangoheadless.org/docs/serializers.md). ## Schema settings `SCHEMA` adds an [OpenAPI schema](https://djangoheadless.org/docs/schema.md) route next to the generated routes; it is `False` by default. `SCHEMA_TITLE`, `SCHEMA_DESCRIPTION` and `SCHEMA_VERSION` fill the `info` of the schema. ## Filter settings These settings configure [`LookupFilter`](https://djangoheadless.org/docs/filtering.md): - **`FILTER_EXCLUSION_SYMBOL`**: the prefix that turns a filter into an exclusion. - **`FILTER_TRUE_VALUES`, `FILTER_FALSE_VALUES`, `FILTER_NULL_VALUES`**: the values read as `True`, `False` and `None`. - **`FILTER_DISALLOWED_LOOKUPS`**: lookups that cannot be used in filters. The default, `["regex", "iregex"]`, blocks regular expressions; see [Filtering](https://djangoheadless.org/docs/filtering.md#disallowed-lookups). - **`NON_FILTER_FIELDS`**: query parameters that are never read as filters. `LookupFilter` also skips the parameters of the other filter backends and the pagination class of a route (such as `SEARCH_PARAM`, `ORDERING_PARAM`, `limit` and `offset`), DRF's `format` parameter and the `expand`, `fields` and `omit` parameters. Add any other parameter your views read here. ## Related pages - [Permissions](https://djangoheadless.org/docs/permissions.md) - [Authentication](https://djangoheadless.org/docs/authentication.md) - [System checks](https://djangoheadless.org/docs/checks.md) # 🩺 System checks Django Headless adds checks to Django's [system check framework](https://docs.djangoproject.com/en/stable/topics/checks/) that catch risky or broken settings before a request does. They run with `runserver`, `migrate` and `python manage.py check`. Run the deployment checks as well before you deploy: ```bash python manage.py check --deploy ``` An error stops `runserver` and other management commands until you fix it. A warning is shown but does not stop anything. | ID | Level | Runs | Issue | | --------------- | ------- | ------------------------ | ------------------------------------------------------- | | `headless.E001` | Error | Always | `SecretKeyAuthentication` is used without a secret key. | | `headless.E002` | Error | Always | The full access key and the read-only key are the same. | | `headless.E003` | Error | Always | The schema is enabled, but its packages are missing. | | `headless.E004` | Error | Always | A search field cannot be searched. | | `headless.W001` | Warning | With `--deploy` | A secret key is weak. | | `headless.W002` | Warning | Always | Anyone can change the content of exposed models. | | `headless.W003` | Warning | With `--deploy` | No authentication classes are configured. | | `headless.W004` | Warning | With `--deploy` | List routes are not paginated. | | `headless.W005` | Warning | Always | `HEADLESS` has a key that is not a setting. | | `headless.W006` | Warning | Always | A field that looks like a credential is serialized. | | `headless.W007` | Warning | Always | A user model is exposed without a `fields` list. | | `headless.W008` | Warning | Always | A model is exposed more than once with other options. | | `headless.W009` | Warning | Always | An exposed model has no routes. | | `headless.W010` | Warning | Always | Models are exposed, but `headless.rest` is not installed. | | `headless.W011` | Warning | Always | A search field searches a field that is not serialized. | ## `headless.E001` `SecretKeyAuthentication` is used on the generated routes or in `REST_FRAMEWORK`, but neither `HEADLESS["AUTH_SECRET_KEY"]` nor `HEADLESS["AUTH_READ_ONLY_SECRET_KEY"]` is set. Every request that the class handles fails. Set one of the keys, or both; see [Authentication](https://djangoheadless.org/docs/authentication.md#secret-key-authentication). ## `headless.E002` `AUTH_SECRET_KEY` and `AUTH_READ_ONLY_SECRET_KEY` have the same value, so the API cannot tell a full access request from a read-only one, and every request with the key fails. Use a different value for each key. ## `headless.E003` `HEADLESS["SCHEMA"]` is enabled, but the `uritemplate` or `inflection` package that generates the [OpenAPI schema](https://djangoheadless.org/docs/schema.md) is not installed, so the schema route fails. Install them with the `schema` extra: ```bash pip install "django-headless[schema]" ``` ## `headless.E004` A name in the `search_fields` option of a model cannot be searched, so every request with `?search=` would fail. Either a part of the name after the first is not a field of the related model, as in `category__nmae`, or the name ends on a relation, as in `category`. Name a text field of the related model instead: ```python # blog/models.py @expose(search_fields=["title", "category__name"]) class Article(models.Model): ... ``` ## `headless.W001` A secret key is shorter than 32 characters, has fewer than five unique characters, or is an example value from this documentation, such as `your-secret-key`. A short key can be guessed. Generate a long random key: ```bash python -c "import secrets; print(secrets.token_urlsafe(48))" ``` ## `headless.W002` The generated routes allow every request (`AllowAny`, or no permission classes) and at least one exposed model is not read-only, so anyone can create, change and delete its content. The warning lists those models. To serve content publicly and accept changes only from authenticated clients, use `IsAuthenticatedOrReadOnly`, or expose models that are only read with `read_only=True`; see [Permissions](https://djangoheadless.org/docs/permissions.md#public-content). If anyone may change the content on purpose, silence the warning. ## `headless.W003` Neither `REST_FRAMEWORK` nor `HEADLESS` sets authentication classes, so the generated routes use Django REST Framework's defaults: session and basic authentication. With basic authentication, clients send a username and password with every request, and Django REST Framework does not limit failed attempts. Set the authentication classes the API needs; see [Authentication](https://djangoheadless.org/docs/authentication.md#other-authentication-classes). If you configure `BasicAuthentication` yourself, the warning does not apply. ## `headless.W004` The list routes have no pagination class, or a pagination class without a page size, so a single request returns every object of a model. Set a pagination class and a page size; see [Pagination](https://djangoheadless.org/docs/pagination.md): ```python # mysite/settings.py HEADLESS = { "DEFAULT_PAGINATION_CLASS": "headless.rest.pagination.PageNumberPagination", "PAGE_SIZE": 25, } ``` ## `headless.W005` `HEADLESS` has a key that is not a Django Headless setting, usually a typo such as `PAGESIZE` for `PAGE_SIZE`. The key has no effect, so the default applies instead, which matters most for settings such as `DEFAULT_PERMISSION_CLASSES`. The hint suggests the closest setting name; see the [settings reference](https://djangoheadless.org/docs/settings.md) for all names. `HEADLESS` itself must be a dictionary. Any other value raises `ImproperlyConfigured` when the project starts. ## `headless.W006` An exposed model serializes a field whose name looks like a credential, and the field is not named in its `fields` option. A name counts when one of its parts (split on `_`) is `password`, `passwd`, `pwd`, `secret`, `token`, `otp`, `salt` or `apikey`, or when it contains `api_key`, `private_key` or `access_key`. For example, `password_hash`, `access_token` and `stripe_api_key` count, and `sort_key` and `tokenizer` do not. The warning names the model and the field. Leave the field out with `exclude`. A field that is left out can still be a [lookup field](https://djangoheadless.org/docs/models.md#lookup-routes), for example a share token that fetches an object without appearing in the response: ```python # blog/models.py from django.db import models from headless import expose @expose(exclude=["share_token"], lookup_fields=["share_token"]) class Article(models.Model): title = models.CharField(max_length=200) share_token = models.CharField(max_length=64, unique=True) ``` If the API should serialize the field, name it in `fields`: a field listed there is a deliberate choice and does not trigger the warning. ## `headless.W007` A user model, a subclass of Django's `AbstractBaseUser` such as `django.contrib.auth.models.User`, is exposed without a `fields` option. Such a model holds the password hash, the email address, permissions and login data, and `exclude` easily misses one. List the fields the API may serialize: ```python # blog/models.py from django.contrib.auth.models import User from headless import expose_model expose_model(User, fields=["username", "first_name", "last_name"]) ``` ## `headless.W008` A model is exposed more than once with different options, for example with `@expose()` on the model and `expose_model()` elsewhere. Only the last registration is in effect, so options of the earlier one are lost. Expose the model once, with all its options. Exposing a model again with the same options does not trigger the warning. ## `headless.W009` A model is exposed but has no routes. Django Headless builds the routes when the `headless.rest` app is ready, so a model exposed after that, for example with `expose_model()` in the `ready()` method of an app listed after `headless.rest` in `INSTALLED_APPS`, is never added. Call `expose_model()` in a models module, or in the `ready()` method of an app listed before `headless.rest`; see [Exposing models](https://djangoheadless.org/docs/models.md). ## `headless.W010` Models are exposed, but `headless.rest`, the app that serves them, is not in `INSTALLED_APPS`, so the API has no routes. `headless` only keeps track of the exposed models. Add `headless.rest` after `headless`; see [Installation](https://djangoheadless.org/docs/installation.md): ```python # mysite/settings.py INSTALLED_APPS = [ # ... "rest_framework", "headless", "headless.rest", ] ``` ## `headless.W011` A name in the `search_fields` option of a model searches a field that the API does not serialize: a field left out with `fields` or `exclude`, on the model itself or on a related model, or a field of a model that is not exposed. The values of such a field never appear in a response, but anyone who may search can find them out one guess at a time: `?search=abc` answers the object when the hidden value contains `abc`. That is fine for a field that is only hidden to keep responses small, such as search keywords or a long body text. It is not for a field that is hidden because it is private. Remove the field from `search_fields`, or [silence the check](#silencing-a-check) when searching it is intended. ## Silencing a check To accept a warning on purpose, add its ID to Django's [`SILENCED_SYSTEM_CHECKS`](https://docs.djangoproject.com/en/stable/ref/settings/#silenced-system-checks) setting: ```python # mysite/settings.py SILENCED_SYSTEM_CHECKS = ["headless.W002"] ``` ## Related pages - [Authentication](https://djangoheadless.org/docs/authentication.md) - [Permissions](https://djangoheadless.org/docs/permissions.md) - [Settings reference](https://djangoheadless.org/docs/settings.md) # 🤖 AI agents AI coding agents, such as Claude Code, Codex or Cursor, can set up Django Headless and write frontend code against the API. Give them the Django Headless skill or the Markdown version of this documentation, so they use the decorator options and settings instead of writing serializers and viewsets by hand. ## Agent skill The Django Headless skill is a `SKILL.md` file in the [Agent Skills](https://agentskills.io) format. It covers the setup, the `@expose()` options, permissions and authentication, the query parameters of the API and the TypeScript client. An agent loads it when a task involves Django Headless. In Claude Code, install it as a plugin: ```text /plugin install django-headless --marketplace dwarsbit/django-headless ``` For other agents, install it with the [skills](https://www.npmjs.com/package/skills) command, which asks which agents to install it for: ```bash npx skills add dwarsbit/django-headless ``` To install it by hand, copy the [`skills/django-headless`](https://github.com/dwarsbit/django-headless/tree/main/skills/django-headless) folder of the repository into the skills folder of your agent, such as `.claude/skills/` in your project. ## Documentation for agents This documentation is also available as Markdown, following the [llms.txt](https://llmstxt.org) convention: - [`/llms.txt`](https://djangoheadless.org/llms.txt): an index of the pages, with a link to the Markdown of each page. - [`/llms-full.txt`](https://djangoheadless.org/llms-full.txt): every page in one file. - `/docs/.md`: the Markdown of one page, such as [`/docs/filtering.md`](https://djangoheadless.org/docs/filtering.md). Point an agent that has no skills to `https://djangoheadless.org/llms.txt`, for example in the `AGENTS.md` of your project. ## Related pages - [Installation](https://djangoheadless.org/docs/installation.md) - [TypeScript client](https://djangoheadless.org/docs/client.md)