# Add API Key Authentication to a FastAPI App on SQLModel

Yes. An agent adds a hashed API key table, routes to issue and revoke keys, a dependency that accepts a key beside the JWT, a migration and tests, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-api-key-auth/sqlmodel/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how a request is authenticated today. In a backend laid out like fastapi/full-stack-fastapi-template, `app/api/deps.py` declares `reusable_oauth2` as an `OAuth2PasswordBearer` pointing at `/login/access-token`, and `get_current_user` decodes the bearer as an HS256 JWT with `settings.SECRET_KEY`, reads `TokenPayload.sub`, answers 403 on a bad token, 404 on an unknown user and 400 on an inactive one; `CurrentUser` is the `Annotated` dependency every route takes. `app/models.py` defines `User` and `Item` with UUID primary keys, a `created_at` set by `get_datetime_utc`, and an `ondelete="CASCADE"` foreign key from items to users. `app/core/security.py` hashes passwords with `pwdlib` using Argon2 and bcrypt. Alembic's latest revision is `fe56fa70289e` and its `env.py` autogenerates from `SQLModel.metadata`. Tests use a session-scoped database fixture in `tests/conftest.py` that deletes items and users at the end, and `scripts/test.sh` runs them under `coverage`, which CI holds at 90 percent.

It adds the key as a table and keeps the secret out of it. A new `ApiKey` model in `app/models.py` has a UUID id, a `user_id` foreign key with `ondelete="CASCADE"` so deleting a user removes their keys the way it removes their items, a `name`, a `key_prefix` of the first characters for display and lookup, a `hashed_key`, `created_at`, an optional `expires_at`, `last_used_at` and `revoked_at`. The plaintext is `sk_` followed by `secrets.token_urlsafe`, shown once in the create response and hashed with SHA-256 for storage, since a key this random gains nothing from a slow password hash and the lookup runs on every request. The agent generates the migration with `alembic revision --autogenerate`, reads the file it produces and keeps it as the revision after `fe56fa70289e`.

Then the routes and the dependency. `app/api/routes/api_keys.py` adds `POST`, `GET` and `DELETE` under `/users/me/api-keys`, each taking `CurrentUser`, so only a signed-in person issues or revokes their own keys, and the delete sets `revoked_at` rather than removing the row so a key's history survives. In `deps.py` the agent sets `auto_error=False` on the OAuth2 scheme, adds an `APIKeyHeader` for `X-API-Key` with the same setting, and changes `get_current_user` to try the JWT when a bearer is present, else look the key up by prefix, compare hashes with `hmac.compare_digest`, refuse an expired or revoked key with 403, stamp `last_used_at`, and refuse with 401 when neither credential was sent. Every existing route keeps its `CurrentUser` signature, so the generated frontend client and `scripts/generate-client.sh` need no change beyond the new routes.

Tests go in `tests/api/routes/test_api_keys.py` in the style of `test_login.py`: create a key with `normal_user_token_headers`, call `/login/test-token` with only `X-API-Key` and read back the same user, revoke it and get 403, send a made-up key and get 403, and send nothing and get 401. The agent starts PostgreSQL in its sandbox with the `prestart.sh` migration step from `test-backend.yml`, runs `scripts/test.sh`, `ruff check`, `mypy` in the project's strict mode and `ty`, and keeps the output.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add API key authentication beside the JWT. Read backend/app/api/deps.py, backend/app/models.py, backend/app/core/security.py, backend/app/crud.py, backend/app/api/routes/login.py, backend/app/api/routes/users.py, backend/app/api/main.py, backend/app/alembic/env.py, the latest file under backend/app/alembic/versions, backend/tests/conftest.py, backend/tests/api/routes/test_login.py and backend/scripts/test.sh first. Add an ApiKey table model with a user_id foreign key that cascades on delete, name, key_prefix, hashed_key, created_at, expires_at, last_used_at and revoked_at; generate the plaintext as sk_ plus secrets.token_urlsafe, return it once, and store a SHA-256 hash. Add POST, GET and DELETE routes under /users/me/api-keys for the signed-in user, where delete sets revoked_at. Change get_current_user to accept either a bearer JWT or an X-API-Key header, refusing expired and revoked keys with 403 and a missing credential with 401. Generate the Alembic migration with autogenerate and keep it. Write tests in the style of test_login.py. Run scripts/test.sh against a local PostgreSQL, ruff, mypy and ty, and open a pull request with the output.",
  "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 `ApiKey` model, one migration, `app/api/routes/api_keys.py`, its registration in `app/api/main.py`, the changed dependency in `deps.py` and `tests/api/routes/test_api_keys.py`. The description shows the dependency's decision order, the request and response of each new route with the plaintext shown once, the migration's upgrade and downgrade, and the test, lint and type-check output.

The run's record keeps the coverage report, so a reviewer sees that the new routes and both branches of the dependency are covered and that the project's 90 percent threshold still holds. A reviewer checks that a revoked key is refused on the very next request, that the prefix lookup cannot match two keys, and that the frontend client is regenerated in a follow-up if the dashboard should list keys.

## Run it on every Linear issue labelled api-access

A team makes this a rule. In the Project for the repository, an automation with the prompt above and a `linear` trigger on `linear.issue.labeled` for the label `api-access` starts a run when someone files "a customer wants to call the API from a script" or "keys should expire". The trigger adds the issue after the prompt, so the run reads whether the issue asks for expiry, scopes or a dashboard page and limits the change to that.

Each run opens its own pull request on its own branch and links the issue. A repository that already has a key table gets a description saying so and a pull request only for the part the issue asks for, such as the expiry check.

## Why run it on Rush?

Every API that people call from scripts needs keys, and the places this goes wrong are the same everywhere: a plaintext column, a lookup that compares strings with equals, a revoke that deletes the row and the audit trail with it, and a dependency that quietly stops checking the JWT. The agent reads the existing dependency and models in its sandbox, keeps every route's signature, runs the migration against a real database and writes the tests for each refusal, so the pull request carries evidence for every branch.

The pull request is one model, one migration, three routes and a dependency change, so review is reading the decision order. A company with several FastAPI services runs this on all of them at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Why SHA-256 and not Argon2 like the passwords?

A password is short and guessable, so it needs a slow hash. A key here is random bytes from `secrets.token_urlsafe`, which cannot be guessed, and its hash is checked on every request, so a fast hash is the right choice. The compare uses `hmac.compare_digest` so timing reveals nothing.

### Does the JWT login still work?

Yes. A bearer token is tried first, exactly as before, and the key is read only when no bearer was sent. Every existing test in `test_login.py`, `test_users.py` and `test_items.py` runs unchanged, and the agent includes their output.

### What about per-key scopes?

Not in this pull request. A key acts as its user, with the same `is_superuser` check routes already apply. The model leaves room for a scopes column, and the description says where the dependency would read it.

### Will the frontend show keys?

The backend routes are in this pull request and appear in the OpenAPI document, so running `scripts/generate-client.sh` adds them to the generated `UsersService`. A settings page that lists and revokes keys is a separate run, and the description names the files it would touch.

## More SQLModel jobs

- [Add an Audit Log to a SQLModel App](https://getrush.ai/run/add-audit-log/sqlmodel/)
- [Add Cursor Pagination to a SQLModel API](https://getrush.ai/run/add-cursor-pagination/sqlmodel/)
- [Add Database Indexes to a SQLModel App With Alembic](https://getrush.ai/run/add-database-indexes/sqlmodel/)

## The same job on other stacks

- [Add API Key Authentication to a Cloudflare Worker API](https://getrush.ai/run/add-api-key-auth/cloudflare-workers/)
- [Add API Key Authentication to a Django REST Framework Project](https://getrush.ai/run/add-api-key-auth/django-rest-framework/)
- [Add API Key Authentication to a Fiber App](https://getrush.ai/run/add-api-key-auth/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/)
