Skip to content

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 ​

bash
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.

VariableUsed for
MICROAUTH_SECRET_KEYYour API's SDK secret key (mas_...). Required.
MICROAUTH_BASE_URLMicroAuth API base URL. Defaults to https://api.microauth.com.
MICROAUTH_REDIS_URLOptional Redis URL for shared limits, snapshots and the durable usage queue.
MICROAUTH_USAGE_SPOOL_PATHOptional 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.

bash
# .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.

python
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.

OptionDefaultWhat it does
secret_keyMICROAUTH_SECRET_KEYSDK secret key (mas_...)
base_urlhttps://api.microauth.comMicroAuth API base (MICROAUTH_BASE_URL)
header_nameX-API-KeyHeader your customers send their key in
redis_urlMICROAUTH_REDIS_URLShares limits, snapshots and pending usage across processes
redis_clientNoneAn externally owned redis.asyncio client, used instead of redis_url
redis_max_connections64Cap for the pool built from redis_url. Requests wait up to one second for a free connection
shared_snapshot_cacheTrueWith Redis, share snapshots and coordinate refreshes so cold starts do not all fetch at once
sync_interval30Seconds between snapshot refreshes
report_interval5Usage flushes when 500 requests queue up or this many seconds pass, whichever is first
flush_on_responseAutoTrue on Vercel and AWS Lambda. Checks for a due batch after each response
trailing_flushFalseKeeps a serverless invocation alive until the batch deadline so the last burst is reported
max_snapshot_age300With fail_open=False, requests get 503 once the snapshot is this old
max_stale_snapshot_age3 × max_snapshot_ageHard ceiling for serving known keys from stale data
fail_openTrueKeep serving known keys from a stale snapshot until the hard ceiling
enforce_balanceTrueReturn 402 when a paying customer has no credit left
enforce_quotaTrueReturn 429 when the monthly quota is used up
enforce_rpsTrueApply per-customer requests per second limits
enforce_platform_allowanceTrueReserve against your MicroAuth plan's monthly allowance before the handler runs
verify_negative_ttl30Seconds an unknown key is remembered as invalid
timeout5HTTP timeout in seconds for MicroAuth calls. Each call makes up to three attempts
http_clientNoneAn externally owned httpx.AsyncClient
usage_spool_pathTemp path per APIBase path for the append-only usage journal
persistence_namespaceNoneStable scope for Redis keys and the journal when secrets rotate
persist_usageTrueKeep unacknowledged usage across restarts. Turn off only in tests
max_usage_queue10000Maximum number of reserved and queued usage items
shutdown_timeout10Seconds 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 ​

DependencyResolves toUse it for
Security(auth)CustomerRoutes that require a valid key
Security(auth.optional)Customer | NoneRoutes 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.

FieldTypeMeaning
idstrThe customer's team ID (a UUID). Stable across keys and teammates
key_idstrID of the API key used for this request
statusstrAlways active inside a handler, because suspended customers are rejected first
billing_modelstrpayg, subscription or none
rpsintEffective requests per second limit
price_per_request_microintEffective price per billable request, in micro-USD
monthly_quotaint | NoneEffective monthly request cap, or None for no cap
credit_balance_microintEstimated prepaid balance after this request's reservation
platform_monthly_limitint | NoneYour MicroAuth plan's monthly allowance
platform_monthly_remainingint | NoneAllowance left this month
platform_monthly_period_enddatetime | NoneWhen the allowance resets

Money is always an integer in micro-USD: 1,000,000 is one dollar.

Lifecycle ​

MethodWhen 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.

ExceptionStatusBody detailHeaders
InvalidAPIKey401Invalid or missing API keyWWW-Authenticate: ApiKey header="X-API-Key"
PaymentRequired402Insufficient credit balance
CustomerSuspended403This account is suspended
RateLimited429Rate limit exceededRetry-After
QuotaExceeded429Monthly request quota exceeded
PlatformAllowanceExceeded429Platform monthly request allowance exhausted
AuthUnavailable503Authorization is temporarily unavailable
python
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:

bash
python -m microauth_fastapi check

It checks, in order:

  1. Configuration. The SDK secret key is present and starts with mas_.
  2. 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.
  3. API key. With --key, it explains exactly how a request with that key would be treated: allowed, or refused with 402, 403 or 429 and why.
  4. Shared state. With Redis configured, it confirms Redis is reachable and accepts Lua scripts.
  5. Usage journal. The journal directory is writable.
text
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.
FlagDefaultMeaning
--keynoneA customer API key (map_...) to evaluate
--secret-keyMICROAUTH_SECRET_KEYSDK secret key to test
--base-urlMICROAUTH_BASE_URLControl plane URL
--redis-urlMICROAUTH_REDIS_URLRedis URL to test
--timeout10HTTP 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 a User-Agent: microauth-fastapi/2.9.0 python/3.x header, so support can see which version you run.
  • Snapshots are revalidated with If-None-Match. When nothing changed, MicroAuth answers 304 Not Modified with 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.

MicroAuth is a product of Zyref, LLC.