djangorestframework-api-key
API key permissions for Django REST Framework, with secure hashing and admin-managed keys.
Repository Health
Technical Analysis
djangorestframework-api-key adds API key-based access control to Django REST Framework projects. It ships an abstract API key model, a DRF permission class, and a Django admin integration so you can issue, revoke, and inspect keys without hand-rolling authentication plumbing. Keys are generated as a prefix plus secret pair, hashed with SHA-512 before storage, and never persisted or displayed in plaintext after creation.
The library targets machine-to-machine access — blocking anonymous traffic, throttling by key, or authorizing internal services — rather than user authentication. Its abstract base classes (AbstractAPIKey, BaseHasAPIKey, BaseAPIKeyManager) are the extension points: teams that need custom fields or additional permission logic subclass rather than fork, while the default APIKey/HasAPIKey pairing works out of the box after installing the app and running migrations.
What You Get
- AbstractAPIKey model - an abstract Django model with prefix, hashed key, name, revoked flag, and optional expiry date, ready to subclass or use as-is via the concrete APIKey model.
- HasAPIKey permission class - a DRF permission class that validates an
Authorization: Api-Key <key>header (or a custom header) against stored keys. - Django admin integration - APIKeyModelAdmin shows the generated key exactly once at creation time and prevents un-revoking a key afterward.
- Secure key hashing - keys are generated as a random prefix plus secret pair and hashed with a dedicated SHA-512 password hasher before being stored.
Common Use Cases
- Blocking anonymous traffic - require any caller to present a valid API key before an endpoint responds.
- Authorizing internal services - let an internal frontend or backend service call your API without a full OAuth flow.
- Per-key throttling and usage tracking - log requests by key prefix to see who is calling your API and how often.
Under The Hood
Architecture
The package is a single Django app (src/rest_framework_api_key/) split into clear layers: crypto.py generates and hashes keys via a dedicated KeyGenerator and a custom Sha512ApiKeyHasher wrapping Django’s password-hashing machinery; models.py defines an abstract AbstractAPIKey model plus BaseAPIKeyManager, whose assign_key/create_key methods produce a prefix and hashed-secret pair and store the prefix as an indexed lookup key; permissions.py layers a DRF permission class (BaseHasAPIKey/HasAPIKey) on top, using a KeyParser to pull the key from the Authorization header or a configurable custom header before delegating validation back to the manager. admin.py wires the concrete APIKey model into Django admin, surfacing the generated secret exactly once at creation time. The abstract base classes are the deliberate extension points — teams needing extra fields or custom permission logic subclass AbstractAPIKey, BaseAPIKeyManager, or BaseHasAPIKey rather than modifying the package; changing any of these abstractions would ripple through every downstream subclass and the bundled migrations.
Tech Stack
Targets Python 3.8+ and integrates directly with Django (2.2 through 5.2, per its classifiers) and Django REST Framework, importing rest_framework.permissions and branching on the installed DRF version (via the packaging library) to preserve pre-3.14 object-permission semantics. The build uses setuptools with setuptools-scm for version derivation from git tags, ruff for linting, pytest with pytest-django for the test suite, mkdocs for the published documentation site, and Azure Pipelines for CI across the supported Django/DRF/Python matrix.
Code Quality
Testing is extensive for the package’s size: over a dozen test modules cover models, admin behavior, permission classes (including custom and combined permissions), header parsing, migrations, hasher compatibility, and Django system checks, all run under pytest with the django_db marker. The codebase is fully type-hinted and ships a py.typed marker for downstream type checkers. Error handling is explicit rather than swallowed — revoking a key raises a ValidationError if code attempts to un-revoke it, and DoesNotExist is re-raised deliberately rather than caught silently. Ruff enforces linting in CI.
API Design
The public surface is deliberately small: install the app, run migrations, and add HasAPIKey to a view’s permission_classes — no custom serializers or views required. Keys are only ever shown once, at creation, via the admin’s success message, avoiding a common API-key footgun. The abstract base classes give a documented escape hatch for customization without monkey-patching or forking, and the transparent hasher-upgrade path means operators can change the hashing algorithm without a data migration.