SDK reference
Everything the FastAPI SDK exposes, in one place. For a guided walkthrough with the reasoning behind each setting, read the FastAPI SDK guide.
Current version: 2.9.0. Python 3.10 or newer.
Install
pip install microauth-fastapi
# With Redis support for limits shared across workers
pip install 'microauth-fastapi[redis]'Environment variables
The SDK reads these when the matching constructor argument is not passed.
| Variable | Used for |
|---|---|
MICROAUTH_SECRET_KEY | Your API's SDK secret key (mas_...). Required. |
MICROAUTH_BASE_URL | MicroAuth API base URL. Defaults to https://api.microauth.com. |
MICROAUTH_REDIS_URL | Optional Redis URL for shared limits, snapshots and the durable usage queue. |
MICROAUTH_USAGE_SPOOL_PATH | Optional base path for the local usage journal. |
When one of these is not set in the environment at all, the SDK and the check command read it from a .env file in the working directory. Real environment variables always win, and other entries in the file are ignored, so you do not need python-dotenv or --env-file flags.
# .env
MICROAUTH_SECRET_KEY=mas_...The SDK secret key is shown once, when you launch your API. If you lose it, rotate it in the dashboard under Settings, SDK connection. It starts with mas_. Keep it on the server, never in a browser or mobile app, and keep .env out of version control.
MicroAuth(app, secret_key=None, **options)
Creates the integration and installs a small middleware on app that records the final status code of every authenticated response.
from fastapi import FastAPI, Security
from microauth_fastapi import Customer, MicroAuth
app = FastAPI()
auth = MicroAuth(app)
@app.get("/forecast")
async def forecast(customer: Customer = Security(auth)):
return {"customer": customer.id}If you build the app later, create MicroAuth() without it and call auth.install(app) before the first request.
Options
All options are keyword arguments. Every one has a default, so pass only what you need to change.
| Option | Default | What it does |
|---|---|---|
secret_key | MICROAUTH_SECRET_KEY | SDK secret key (mas_...) |
base_url | https://api.microauth.com | MicroAuth API base (MICROAUTH_BASE_URL) |
header_name | X-API-Key | Header your customers send their key in |
redis_url | MICROAUTH_REDIS_URL | Shares limits, snapshots and pending usage across processes |
redis_client | None | An externally owned redis.asyncio client, used instead of redis_url |
redis_max_connections | 64 | Cap for the pool built from redis_url. Requests wait up to one second for a free connection |
shared_snapshot_cache | True | With Redis, share snapshots and coordinate refreshes so cold starts do not all fetch at once |
sync_interval | 30 | Seconds between snapshot refreshes |
report_interval | 5 | Usage flushes when 500 requests queue up or this many seconds pass, whichever is first |
flush_on_response | Auto | True on Vercel and AWS Lambda. Checks for a due batch after each response |
trailing_flush | False | Keeps a serverless invocation alive until the batch deadline so the last burst is reported |
max_snapshot_age | 300 | With fail_open=False, requests get 503 once the snapshot is this old |
max_stale_snapshot_age | 3 × max_snapshot_age | Hard ceiling for serving known keys from stale data |
fail_open | True | Keep serving known keys from a stale snapshot until the hard ceiling |
enforce_balance | True | Return 402 when a paying customer has no credit left |
enforce_quota | True | Return 429 when the monthly quota is used up |
enforce_rps | True | Apply per-customer requests per second limits |
enforce_platform_allowance | True | Reserve against your MicroAuth plan's monthly allowance before the handler runs |
verify_negative_ttl | 30 | Seconds an unknown key is remembered as invalid |
timeout | 5 | HTTP timeout in seconds for MicroAuth calls. Each call makes up to three attempts |
http_client | None | An externally owned httpx.AsyncClient |
usage_spool_path | Temp path per API | Base path for the append-only usage journal |
persistence_namespace | None | Stable scope for Redis keys and the journal when secrets rotate |
persist_usage | True | Keep unacknowledged usage across restarts. Turn off only in tests |
max_usage_queue | 10000 | Maximum number of reserved and queued usage items |
shutdown_timeout | 10 | Seconds allowed for the final usage drain |
Clients you pass in through redis_client or http_client stay yours. The SDK uses them but never closes them.
Dependencies
| Dependency | Resolves to | Use it for |
|---|---|---|
Security(auth) | Customer | Routes that require a valid key |
Security(auth.optional) | Customer | None | Routes that serve anonymous and authenticated callers |
Both add an APIKeyHeader security scheme to your OpenAPI schema, so the Authorize button in Swagger UI works without extra setup.
Customer
The principal your handler receives. It is a frozen dataclass.
| Field | Type | Meaning |
|---|---|---|
id | str | The customer's team ID (a UUID). Stable across keys and teammates |
key_id | str | ID of the API key used for this request |
status | str | Always active inside a handler, because suspended customers are rejected first |
billing_model | str | payg, subscription or none |
rps | int | Effective requests per second limit |
price_per_request_micro | int | Effective price per billable request, in micro-USD |
monthly_quota | int | None | Effective monthly request cap, or None for no cap |
credit_balance_micro | int | Estimated prepaid balance after this request's reservation |
platform_monthly_limit | int | None | Your MicroAuth plan's monthly allowance |
platform_monthly_remaining | int | None | Allowance left this month |
platform_monthly_period_end | datetime | None | When the allowance resets |
Money is always an integer in micro-USD: 1,000,000 is one dollar.
Lifecycle
| Method | When to call it |
|---|---|
auth.install(app) | Only if you did not pass app to the constructor |
await auth.startup() | Optional. Loads the first snapshot eagerly instead of on the first request |
await auth.aclose() | During graceful shutdown, so pending usage drains. The installed middleware calls it for you on app shutdown |
Errors returned to callers
Each rejection is a subclass of AuthDenied, which is a FastAPI HTTPException. Register a handler for AuthDenied to reshape the body.
| Exception | Status | Body detail | Headers |
|---|---|---|---|
InvalidAPIKey | 401 | Invalid or missing API key | WWW-Authenticate: ApiKey header="X-API-Key" |
PaymentRequired | 402 | Insufficient credit balance | |
CustomerSuspended | 403 | This account is suspended | |
RateLimited | 429 | Rate limit exceeded | Retry-After |
QuotaExceeded | 429 | Monthly request quota exceeded | |
PlatformAllowanceExceeded | 429 | Platform monthly request allowance exhausted | |
AuthUnavailable | 503 | Authorization is temporarily unavailable |
from fastapi.responses import JSONResponse
from microauth_fastapi import AuthDenied
@app.exception_handler(AuthDenied)
async def auth_denied(request, exc):
return JSONResponse(
status_code=exc.status_code,
content={"error": exc.detail, "docs": "https://docs.yourapi.com/errors"},
headers=exc.headers or {},
)Operational problems on your side raise subclasses of MicroAuthError instead, for example MicroAuthConfigurationError for a missing secret key or UsageQueueFull when max_usage_queue is reached. These show up in your logs, not in responses to your customers.
The check command
check confirms an integration end to end without serving traffic or reporting usage. Run it where your API runs, with the same environment variables:
python -m microauth_fastapi checkIt checks, in order:
- Configuration. The SDK secret key is present and starts with
mas_. - Control plane. MicroAuth accepts the secret and returns a snapshot. It prints your API's name, the number of customers and keys, your billable status codes and the platform allowance used this month. It warns when this machine's clock is more than 30 seconds off.
- API key. With
--key, it explains exactly how a request with that key would be treated: allowed, or refused with402,403or429and why. - Shared state. With Redis configured, it confirms Redis is reachable and accepts Lua scripts.
- Usage journal. The journal directory is writable.
MicroAuth FastAPI SDK 2.9.0
Configuration
ok SDK secret key mas_...v6a9
ok control plane https://api.microauth.com
Control plane
ok connected to Weather API
ok snapshot loaded: 12 customer(s), 19 key(s)
billable status codes: 200
platform allowance: 48,210 of 10,000,000 requests used this month
API key
ok key belongs to customer 7c1d0a52-6f3e-4f0e-9a51-0c2f6a1d2b77
plan source: payg, billing: payg
balance: $0.999
price per billable request: $0.001
rate limit: 10 requests per second
ok a request with this key would be allowed
Shared state
ok no Redis configured; each worker enforces limits on its own
Usage journal
ok usage journal directory is writable (/tmp)
Everything looks good. Your API is ready to serve keys.| Flag | Default | Meaning |
|---|---|---|
--key | none | A customer API key (map_...) to evaluate |
--secret-key | MICROAUTH_SECRET_KEY | SDK secret key to test |
--base-url | MICROAUTH_BASE_URL | Control plane URL |
--redis-url | MICROAUTH_REDIS_URL | Redis URL to test |
--timeout | 10 | HTTP timeout in seconds |
The command exits with 0 when everything passed and 1 when any line reads fail, so it works as a deploy smoke test in CI. On failure it ends with a link to troubleshooting. The secret key, base URL and Redis URL are read from .env too when they are not in the environment (see environment variables).
What the SDK sends
- Every call carries
Authorization: Bearer mas_...and aUser-Agent: microauth-fastapi/2.9.0 python/3.xheader, so support can see which version you run. - Snapshots are revalidated with
If-None-Match. When nothing changed, MicroAuth answers304 Not Modifiedwith no body, which keeps refreshes cheap for APIs with many customers. - Usage goes out in batches of up to 500 items to
POST /sdk/v1/usage. Each item keeps the same idempotency key across retries until MicroAuth acknowledges it.
The endpoints themselves are documented in the custom integration guide and the API reference.