# Add API Key Authentication to a Django REST Framework Project

Yes. An agent adds hashed, revocable API keys with an authentication class, endpoints to issue and revoke them, tests for each path, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-api-key-auth/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 how the project authenticates today so the new scheme fits beside the old ones. In a project shaped like HackSoftware/Django-Styleguide-Example, `requirements/base.txt` pins `Django` 5.2.7, `djangorestframework` 3.16.1 and `drf-jwt` 1.19.2, and `requirements/local.txt` adds `pytest` 8.4.2 with `pytest-django`, `factory-boy`, `mypy` 1.18.2 with `django-stubs` and `djangorestframework-stubs`, and `ruff` 0.14.0. `REST_FRAMEWORK` in `config/django/base.py` sets `DEFAULT_AUTHENTICATION_CLASSES` to an empty list; instead `styleguide_example/api/mixins.py` defines `ApiAuthMixin` with `CsrfExemptedSessionAuthentication`, `SessionAsHeaderAuthentication`, which reads `Authorization: Session <key>`, and `JSONWebTokenAuthentication`, and every protected view mixes it in. `authentication/urls.py` has session and JWT login and logout and `me/`; `authentication/apis.py` shows the house style, an `APIView` with a nested `InputSerializer` calling a service. `users/models.py` defines `BaseUser` on `common.models.BaseModel`, which gives `created_at` and `updated_at`, with `email` as `USERNAME_FIELD` and a `jwt_key` the logout service rotates. `authentication/tests/apis/test_user_login.py` is a `TestCase` with `APIClient`, `reverse("api:authentication:session:login")` and `user_create`.

It adds an `api_keys` app in the project's layout: `models.py`, `services.py`, `selectors.py`, `apis.py`, `urls.py`, `admin.py` and a `tests/` package. `ApiKey` extends `BaseModel` with a `user` foreign key to `BaseUser`, a `name`, a short `prefix` that is unique and indexed, a `hashed_key`, and nullable `expires_at`, `revoked_at` and `last_used_at`. The raw key is `<prefix>.<secret>`, generated with `secrets.token_urlsafe`, hashed with Django's `make_password` and never stored, so a database read cannot be replayed as a key. `api_key_create(*, user, name, expires_at=None)` returns the model and the raw key once, `api_key_revoke(*, api_key)` sets `revoked_at`, and `api_key_authenticate(*, raw_key)` splits on the dot, looks the prefix up, runs `check_password`, refuses a revoked or expired row, and updates `last_used_at` with `update_fields` so the write is one column.

`ApiKeyAuthentication` goes in `api/mixins.py` next to the other classes: it reads the `Authorization` header through the existing `get_auth_header`, returns `None` unless the scheme is `Api-Key` so the other authenticators keep their turn, calls the service, and raises `AuthenticationFailed` for a bad key. It is appended to `ApiAuthMixin.authentication_classes`, so every view that already uses the mixin accepts a key with no edit. The management APIs sit under `auth/api-keys/` with a `api-keys` namespace: `ApiKeyCreateApi` takes `name` and an optional `expires_at` and answers the raw key once, `ApiKeyListApi` lists the caller's keys with prefix, name, dates and never the hash, and `ApiKeyRevokeApi` revokes one of the caller's keys by id; all three use `ApiAuthMixin`, so a key cannot mint another key unless the reviewer decides it should. A migration comes from `makemigrations api_keys`, and `admin.py` registers the model read-only on `hashed_key`.

Tests go in `api_keys/tests/apis/test_api_key_auth.py` and `api_keys/tests/services/test_api_key_create.py` in the login test's style. One creates a user with `user_create`, logs in through the session endpoint, creates a key, then calls `me/` with `Authorization: Api-Key <raw>` from a fresh `APIClient` and asserts `200`. Others assert that a wrong secret with a real prefix is `403`, that a revoked key and an expired key are refused, that the list never contains the hash, that `last_used_at` is set after one use, and that the service's hash verifies against the raw key and nothing else. Before pushing the agent runs `ruff check .`, `mypy --config mypy.ini styleguide_example/` with the Django and DRF plugins, and `pytest`, the three commands in `.github/workflows/django.yml`, and pastes the results into the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add API key authentication to this Django REST Framework project and open a pull request. Read config/django/base.py, styleguide_example/api/urls.py, styleguide_example/api/mixins.py, styleguide_example/authentication/urls.py, styleguide_example/authentication/apis.py, styleguide_example/authentication/services.py, styleguide_example/authentication/tests/apis/test_user_login.py, styleguide_example/users/models.py, styleguide_example/users/services.py, styleguide_example/common/models.py, mypy.ini and .github/workflows/django.yml first. Add an api_keys app with an ApiKey model on BaseModel: user, name, unique prefix, hashed_key, nullable expires_at, revoked_at and last_used_at. Generate keys as <prefix>.<secret> with secrets.token_urlsafe, store only make_password of the secret, and return the raw key once from api_key_create. Add api_key_revoke and api_key_authenticate services. Add ApiKeyAuthentication to api/mixins.py reading an Api-Key scheme through get_auth_header and returning None for other schemes, and append it to ApiAuthMixin.authentication_classes. Mount ApiKeyCreateApi, ApiKeyListApi and ApiKeyRevokeApi under auth/api-keys/ with an api-keys namespace, all behind ApiAuthMixin, in the nested InputSerializer style. Add the migration and an admin registration. Write tests covering a key used on me/, a wrong secret, a revoked key, an expired key, the list never showing the hash and last_used_at being set. Run ruff check ., mypy --config mypy.ini styleguide_example/ and pytest and paste the results in the pull request. Do not change the session or JWT flows.",
  "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 that adds the `api_keys` app with its model, migration, services, selectors, APIs, urls, admin and tests, adds the app to `INSTALLED_APPS`, adds one authentication class and one list entry to `api/mixins.py`, and one `include` to `authentication/urls.py`. The session and JWT code is untouched. The description shows a create response with the raw key, a `me/` call with the `Api-Key` header, explains why only the hash is stored, and pastes the `ruff`, `mypy` and `pytest` output.

On a repository with the `Django application` workflow, the pull request builds the Docker image and runs `ruff check`, `mypy` and `py.test` inside it, then runs the same three against a Postgres service, so a missing type hint on the new service or a migration that does not match the model fails in both jobs.

A reviewer checks whether keys should be allowed to manage keys, whether a default expiry should be required, and how the prefix is shown in their logs, since it is the one part of a key that is safe to print. Then they decide which views outside `ApiAuthMixin` should accept keys.

## Run it on every Django service that machines need to call

A team with several Django REST Framework services sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own authentication setup, so a project with `DEFAULT_AUTHENTICATION_CLASSES` set globally gets the class added there instead of to a mixin, and each run opens its own pull request.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request and the test output from.

## Why run it on Rush?

API key code is security code with quiet failure modes: a key stored in clear, a revoked key that still works because one view skipped the check, an expiry compared in the wrong timezone. In a Rush sandbox the agent runs the project's own `pytest` with tests for each of those paths against the real authentication stack, runs `mypy` with the Django and DRF stubs over the new app, and keeps every command and its output in the run's record, so the pull request shows the refusals happening rather than asserting they would.

The scheme slots into `ApiAuthMixin` beside session and JWT authentication, so every protected view accepts a key with no per-view change, and it reuses Django's password hashing and the project's service and selector layout. No package is added. The same request works on any Django REST Framework project with a custom user model.

## Frequently asked questions

### Why store a hash and show the key once?

So that reading the database, a backup or a log never yields a usable key. The secret half is hashed with `make_password` and verified with `check_password`; the prefix is stored in clear so a key can be found and named in logs. The create response is the only place the raw key appears, and the list endpoint test asserts the hash is never returned.

### Does it change how the session and JWT logins work?

No. `ApiKeyAuthentication` returns `None` for any `Authorization` scheme other than `Api-Key`, so the session and JWT authenticators run exactly as before, and the login, logout and `me/` endpoints are unchanged. The only edit in `api/mixins.py` is the new class and its entry in the list.

### Can a request made with a key create more keys?

As written, yes, because the management APIs use `ApiAuthMixin` like every other view. The pull request points at the one permission check to add if keys should be minted only by a session or JWT login, which is a common policy.

### How is expiry handled?

`expires_at` is optional and compared with `timezone.now()` in the authenticate service, so a key with no expiry lives until it is revoked. A reviewer who wants every key to expire makes the field required in the input serializer; the expired-key test shows the refusal.

## More Django REST Framework jobs

- [Add API Versioning to a Django REST Framework Project from a Linear Issue](https://getrush.ai/run/add-api-versioning/django-rest-framework/)
- [Add an Audit Log to a Django REST Framework API from a Linear Issue](https://getrush.ai/run/add-audit-log/django-rest-framework/)
- [Add Test Coverage to CI for a Django REST Framework API](https://getrush.ai/run/add-coverage-to-ci/django-rest-framework/)

## The same job on other stacks

- [Add API Key Authentication to a Fiber App](https://getrush.ai/run/add-api-key-auth/fiber/)
- [Add API Key Authentication to a Koa API](https://getrush.ai/run/add-api-key-auth/koa/)
- [Add API Key Authentication to a Litestar App](https://getrush.ai/run/add-api-key-auth/litestar/)

## 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/)
