# Add Security Headers to a Django REST Framework API

Yes. An agent adds HSTS, referrer, frame and content security headers to your Django REST Framework API production settings, proves them with pytest, in a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-security-headers/django-rest-framework/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the settings before it changes a header. In an API shaped like HackSoftware/Django-Styleguide-Example, requirements/base.txt pins Django 5.2.7, djangorestframework 3.16.1, django-cors-headers 4.9.0, django-structlog 9.1.1, whitenoise 6.11.0 and gunicorn 23.0.0. config/django/base.py builds MIDDLEWARE with SecurityMiddleware first, then CorsMiddleware, WhiteNoise, sessions, CommonMiddleware, CSRF, auth, messages and XFrameOptionsMiddleware, and pulls in config/settings/cors.py, sessions.py, jwt.py and the rest. config/django/production.py sets `SECURE_PROXY_SSL_HEADER`, `SECURE_SSL_REDIRECT` and `SECURE_CONTENT_TYPE_NOSNIFF` from the environment with True defaults, `SESSION_COOKIE_SECURE` the same way, and `CORS_ALLOW_ALL_ORIGINS = False` with a whitelist. Nothing sets `SECURE_HSTS_SECONDS`, `SECURE_HSTS_INCLUDE_SUBDOMAINS`, `SECURE_HSTS_PRELOAD`, `SECURE_REFERRER_POLICY`, `SECURE_CROSS_ORIGIN_OPENER_POLICY` or `X_FRAME_OPTIONS`, so those run on Django's defaults, and there is no Content-Security-Policy or Permissions-Policy at all. config/settings/sessions.py defaults `CSRF_USE_SESSIONS` to True and the session cookie to HttpOnly and Lax; config/settings/jwt.py keeps a `jwt` cookie with `JWT_AUTH_COOKIE_SECURE` on.

`python manage.py check --deploy` with the production settings module is the first thing the agent runs, because Django's checks name what is missing by code; it reads them and then decides each header for an API rather than a website. HSTS goes into production.py with the seconds, include-subdomains and preload flags read from the environment the way the file already reads SSL redirect, with a short default and a comment, because a wrong HSTS value on a shared domain is hard to take back. Referrer-Policy and X-Frame-Options are set explicitly to `same-origin` and `DENY` so the choice is written down rather than inherited. A Content-Security-Policy still matters on an API because DRF's browsable API and the Django admin at /admin/ are HTML pages: on Django 5.2 the agent adds django-csp to requirements/base.txt with a policy that allows the admin's and the browsable API's own scripts and styles and nothing else, and notes that Django 6.0 carries CSP inside SecurityMiddleware so the package can go at the upgrade. A Permissions-Policy that turns off camera, microphone and geolocation is a few lines of middleware in styleguide_example/common, since Django has no setting for it. The CORS whitelist and the cookie settings stay as they are, and a sentence in the README's CORS section points at the new block.

Tests use pytest with pytest-django, `DJANGO_SETTINGS_MODULE = config.django.test` in pytest.ini and the layout of styleguide_example/api/tests. The agent adds styleguide_example/common/tests/test_security_headers.py that requests an API route and the admin login with the test client under `override_settings` for the production values, and asserts each header: HSTS with the configured max-age, nosniff, the referrer policy, the frame option, the CSP on the admin page, the permissions policy on every response, and no HSTS when the seconds are zero. Then it runs what .github/workflows/django.yml runs: `ruff check .`, `mypy --config mypy.ini styleguide_example/` and `pytest` against Postgres, and the docker job's `docker compose build` followed by the same three commands inside the django service.

It finishes by starting gunicorn as docker/web_entrypoint.sh does, with `DJANGO_SETTINGS_MODULE=config.django.production` and the variables the file reads, fetching `/api/users/` and `/admin/login/` with `curl -I` so the pull request shows the headers as the server sends them rather than as the test client sees them, and running `check --deploy` once more to show which warnings are gone.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add security headers to this Django REST Framework API. Read requirements/base.txt, config/django/base.py, production.py and test.py, config/settings/cors.py, sessions.py and jwt.py, config/urls.py, docker-compose.yml, docker/web_entrypoint.sh, pytest.ini, mypy.ini, the README's CORS and sessions sections and .github/workflows/django.yml first, then run manage.py check --deploy with the production settings and read every warning. In production.py add HSTS with seconds, include-subdomains and preload read from the environment with a short default, and explicit referrer policy, frame option and cross-origin opener policy. Add django-csp with a policy that allows only what the admin and the browsable API load, and a small middleware for a Permissions-Policy, registered in base.py. Leave CORS and the cookie settings alone. Write pytest tests under styleguide_example/common/tests that assert each header on an API route and the admin login under override_settings, including no HSTS when the seconds are zero. Run ruff, mypy and pytest as the workflow does, start gunicorn with the production settings and fetch an API route and the admin login with curl -I, run check --deploy again, and open a pull request that quotes the warnings before and after, the test output and the headers.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request on its own branch that changes config/django/production.py, config/django/base.py, requirements/base.txt and README.md, and adds the Permissions-Policy middleware and styleguide_example/common/tests/test_security_headers.py. No view, serializer or URL changes, and the CORS and cookie settings are untouched.

The description lists the `check --deploy` warnings before and after by their codes, quotes the pytest run with the new file among the tests, and shows the `curl -I` output for `/api/users/` and `/admin/login/` from gunicorn under the production settings, so a reviewer sees HSTS, nosniff, the referrer policy, the frame option and the permissions policy on both and the CSP on the admin page.

Before merging, a reviewer sets the HSTS seconds and decides whether preload is wanted (it is a public list and hard to leave), whether the CSP should start in report-only mode, and whether JSON responses need a CSP at all. Each is an environment variable or one setting, and a follow-up on the same session changes it.

## Run it on every API deployed on Django's default headers

This is a change to start from the terminal and read later: one `POST /o/{org}/sessions` with this prompt and the repository in `resources`. The run reads the settings, runs the deployment check, writes the headers and the tests, starts gunicorn to read the headers back and opens the pull request on its own. The sandbox parks with its disk when the turn ends, so `switch the CSP to report-only` as a follow-up wakes it with the containers and the branch in place.

A team with several Django services sends the same body once per repository, one run each, and each run reads that service's own production settings and middleware. Give the API key a `webhook_url` and Rush posts `run.completed` or `run.failed` with the `session_url` when each turn ends, so the pull request links collect in one channel. Send a `request_id` with each body so a retried POST returns the run it already started.

## Why run it on Rush?

Security headers are settings, and settings are only proven by a server: the test client does not run gunicorn, SSL redirect hides behind a proxy header, and HSTS behaves differently once it has been sent. The agent runs the deployment check, the tests and a real gunicorn with the production module in its own sandbox, and the pull request carries the before-and-after warnings and the headers it read rather than a list of settings it set.

The record shows each decision: the transcript has the agent reading that the API serves two HTML surfaces, choosing django-csp on Django 5.2 and writing down when it can go, and keeping HSTS behind the environment. A reviewer who wants report-only or a longer max-age says so and the parked sandbox changes the variable.

## Frequently asked questions

### Why is HSTS read from the environment instead of fixed?

Because once a browser has seen a long HSTS max-age for a domain it keeps enforcing HTTPS there, and preload adds the domain to a public list. production.py already reads SSL redirect from the environment; HSTS follows the same pattern with a short default so staging can differ.

### Does a JSON API need a Content-Security-Policy?

The JSON responses do not, but the Django admin and DRF's browsable API are HTML pages served by the same process, and a CSP is what protects them. The policy allows only their own scripts and styles; a reviewer can narrow it to those paths or run it in report-only mode first.

### Will this change CORS?

No. django-cors-headers, its whitelist and CORS_ALLOW_CREDENTIALS stay exactly as config/settings/cors.py and production.py set them. The new headers sit beside CORS, not in place of it.

### What changes when the project moves to Django 6.0?

Django 6.0 carries CSP settings in SecurityMiddleware, so django-csp can be removed and the policy moved to the built-in settings. The description names the file to change, and everything else in the pull request stays.

### Why a hand-written Permissions-Policy middleware?

Django has no setting for that header, and the middleware is a few lines that set one fixed value. If you prefer a package for it, a follow-up swaps it in without touching the tests' assertions.

## More Django REST Framework jobs

- [Add Soft Delete to a Django REST Framework API](https://getrush.ai/run/add-soft-delete/django-rest-framework/)
- [Add Throttling to a Django REST Framework API from a Linear Issue](https://getrush.ai/run/add-throttling/django-rest-framework/)
- [Turn Sentry Errors Into Fix Pull Requests for a Django REST Framework API](https://getrush.ai/run/fix-sentry-errors/django-rest-framework/)

## The same job on other stacks

- [Add Security Headers to an Echo API](https://getrush.ai/run/add-security-headers/echo/)
- [Add Security Headers and a CSP to an Eleventy Site](https://getrush.ai/run/add-security-headers/eleventy/)
- [Add Security Headers to a Fiber App](https://getrush.ai/run/add-security-headers/fiber/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
