Skip to content

FastAPI Api Key

Python Version from PEP 621 TOML Tested with pytest PyPI version Docs codecov Security: bandit Deps: uv Code style: Ruff

fastapi-api-key provides reusable building blocks to issue, persist, and verify API keys in FastAPI applications. It ships with a domain model, hashing helpers, repository contracts, and an optional FastAPI router for CRUD management of keys.

Features

  • Security-first: secrets are hashed with a salt and a pepper, and never logged or returned after creation
  • Prod-ready: services and repositories are async, and battle-tested

  • Agnostic hasher: you can use any async-compatible hashing strategy (default: Argon2)

  • Agnostic backend: you can use any async-compatible database (default: SQLAlchemy)
  • Connector: create a Typer, FastAPI router wired to api key systems

  • Envvar support: easily configure peppers and other secrets via environment variables

  • Extensible: customize models, repositories, hashers, and services to fit your needs
  • Scopes support: assign scopes to API keys for fine-grained access control

Standards compliance

This library try to follow best practices and relevant RFCs for API key management and authentication:

  • RFC 9110/7235: Router raise 401 for missing/invalid keys, 403 for valid but inactive/expired keys
  • RFC 6750: Supports Authorization: Bearer <api_key> header for key transmission (also supports deprecated X-API-Key header and api_key query param)

How API Keys Work

API Key Format

This is a classic API key if you don't modify the service behavior:

Structure:

{global_prefix}-{delimiter}-{identifier}-{delimiter}-{secret}

Example:

ak-7a74caa323a5410d-mAfP3l6yAxqFz0FV2LOhu2tPCqL66lQnj3Ubd08w9RyE4rV4skUcpiUVIfsKEbzw

  • "-" separators so that systems can easily split
  • Prefix ak (for "Api Key"), to identify the key type (useful to indicate that it is an API key).
  • 16 first characters are the identifier (UUIDv4 without dashes)
  • 48 last characters are the secret (random URL-safe base64 string)

When verifying an API key, the service extracts the identifier, retrieves the corresponding record from the repository, and compares the hashed secret. If found, it hashes the provided secret (with the same salt and pepper) and compares it to the stored hash. If they match, the key is valid.

Schema validation

Here is a diagram showing what happens after you initialize your API key service with a global prefix and delimiter when you provide an API key to the .verify_key() method.

Additional notes

  • Python 3.9+ is required.
  • The library issues warnings if you keep the default pepper; always configure a secret value outside source control.
  • Never log peppers or plaintext API keys, change the pepper of prod will prevent you from reading API keys
  1. Head to the Quickstart to wire the service in a REPL or script.
  2. Browse the Usage section to reuse the example applications that ship with the project.