Adaptable security middlewares for FastAPI: API keys, rate limiting, IP whitelist
Project description
OS FastAPI Middlewares
Simple and adaptable: production-ready security middlewares for FastAPI, including API Key, Rate Limit, and IP Whitelist. Plug in in-memory or Redis providers, or implement your own.
- API Key: validates a key from the request, optionally injects metadata into request.state
- Rate Limit: enforces requests per time window and adds X-RateLimit-* headers
- IP Whitelist: allows only approved IPs or networks (supports CIDR)
Docs: see docs/installation.md, docs/quickstart.md, and docs/advanced.md.
Installation
- Basic:
pip install os-fastapi-middleware - With Redis (optional):
pip install os-fastapi-middleware[redis]
Requirements: Python >= 3.8, FastAPI >= 0.100, Starlette >= 0.27.
Quick example
from fastapi import FastAPI, Request
from os_fastapi_middleware.middleware import APIKeyMiddleware, RateLimitMiddleware, IPWhitelistMiddleware
from os_fastapi_middleware.providers import (
InMemoryAPIKeyProvider,
InMemoryRateLimitProvider,
InMemoryIPWhitelistProvider,
)
app = FastAPI()
api_key_provider = InMemoryAPIKeyProvider(valid_keys={
"account_123": "secret-key-123"
})
rate_limit_provider = InMemoryRateLimitProvider()
ip_whitelist_provider = InMemoryIPWhitelistProvider(allowed_ips=["127.0.0.1"])
app.add_middleware(RateLimitMiddleware, provider=rate_limit_provider, requests_per_window=100, window_seconds=60)
app.add_middleware(APIKeyMiddleware, provider=api_key_provider, include_metadata=True)
app.add_middleware(IPWhitelistMiddleware, provider=ip_whitelist_provider)
@app.get("/secure")
async def secure(request: Request):
return {"hello": request.state.api_key_metadata["account_id"]}
More examples in examples/.
Per-route or route group usage
You can also apply validations selectively to specific routes or route groups using dependencies:
from fastapi import FastAPI, Depends, Request
from os_fastapi_middleware.dependencies import APIKeyDependency, RateLimitDependency, IPWhitelistDependency
from os_fastapi_middleware.providers import (
InMemoryAPIKeyProvider,
InMemoryRateLimitProvider,
InMemoryIPWhitelistProvider,
)
app = FastAPI()
# Configure providers
api_key_provider = InMemoryAPIKeyProvider(valid_keys={"account_123": "secret-key-123"})
rate_limit_provider = InMemoryRateLimitProvider()
ip_whitelist_provider = InMemoryIPWhitelistProvider(allowed_ips=["127.0.0.1"])
# Create dependency instances
api_key_dep = APIKeyDependency(provider=api_key_provider)
rate_limit_dep = RateLimitDependency(provider=rate_limit_provider, requests_per_window=10, window_seconds=60)
ip_whitelist_dep = IPWhitelistDependency(provider=ip_whitelist_provider)
# Public route - no validation
@app.get("/public")
async def public():
return {"message": "This is public"}
# Protected route - API key only
@app.get("/protected", dependencies=[Depends(api_key_dep)])
async def protected():
return {"message": "API key validated"}
# Strict route - multiple validations
@app.get("/admin", dependencies=[Depends(ip_whitelist_dep), Depends(api_key_dep), Depends(rate_limit_dep)])
async def admin():
return {"message": "Admin area with all protections"}
# Route group with shared dependencies
from fastapi import APIRouter
api_router = APIRouter(prefix="/api", dependencies=[Depends(api_key_dep)])
@api_router.get("/data")
async def get_data():
return {"data": "protected by API key"}
@api_router.get("/stats")
async def get_stats():
return {"stats": "also protected by API key"}
app.include_router(api_router)
See examples/selective_routes.py for more details.
Key features
- Pluggable providers: in-memory, Redis, and base classes to customize
- Clear configuration: sensible, named parameters
- Rate limit headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
- Works behind proxies (X-Forwarded-For) when enabled
Tests
Install dev dependencies and run:
pip install -e .[dev]
pytest -q
License
MIT. See LICENSE if available.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file os-fastapi-middleware-1.1.10.tar.gz.
File metadata
- Download URL: os-fastapi-middleware-1.1.10.tar.gz
- Upload date:
- Size: 20.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
876ced4343126bc84671dcb1a82087a9e523826b741b4395fb262b2bf196e6db
|
|
| MD5 |
3697a859c53c767b149977866a4bd888
|
|
| BLAKE2b-256 |
9ed9873c3bcb59346e9df6ebc00ecf7f8973ebb669e45e61aba5c700ca1499e4
|
Provenance
The following attestation bundles were made for os-fastapi-middleware-1.1.10.tar.gz:
Publisher:
workflow.yml on tcharrua-odds/os-fastapi-middleware
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
os_fastapi_middleware-1.1.10.tar.gz -
Subject digest:
876ced4343126bc84671dcb1a82087a9e523826b741b4395fb262b2bf196e6db - Sigstore transparency entry: 610949262
- Sigstore integration time:
-
Permalink:
tcharrua-odds/os-fastapi-middleware@803fc7c8c67fd5f15b3a30aee170322d0d822ded -
Branch / Tag:
refs/tags/1.1.10 - Owner: https://github.com/tcharrua-odds
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
workflow.yml@803fc7c8c67fd5f15b3a30aee170322d0d822ded -
Trigger Event:
release
-
Statement type:
File details
Details for the file os_fastapi_middleware-1.1.10-py3-none-any.whl.
File metadata
- Download URL: os_fastapi_middleware-1.1.10-py3-none-any.whl
- Upload date:
- Size: 23.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
11812acd9c1f48b26a69207fdd4fb8d8dde91cfe89ffff598316d17f9de67af8
|
|
| MD5 |
41f735f085a97dfb2cb0e6e90662595b
|
|
| BLAKE2b-256 |
4d08afa47362ede5c69cd2e2110d9e7197c2a03fb74832427e53936ed948bcb1
|
Provenance
The following attestation bundles were made for os_fastapi_middleware-1.1.10-py3-none-any.whl:
Publisher:
workflow.yml on tcharrua-odds/os-fastapi-middleware
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
os_fastapi_middleware-1.1.10-py3-none-any.whl -
Subject digest:
11812acd9c1f48b26a69207fdd4fb8d8dde91cfe89ffff598316d17f9de67af8 - Sigstore transparency entry: 610949287
- Sigstore integration time:
-
Permalink:
tcharrua-odds/os-fastapi-middleware@803fc7c8c67fd5f15b3a30aee170322d0d822ded -
Branch / Tag:
refs/tags/1.1.10 - Owner: https://github.com/tcharrua-odds
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
workflow.yml@803fc7c8c67fd5f15b3a30aee170322d0d822ded -
Trigger Event:
release
-
Statement type: