HUB
Sign inSign up

usagerail/fastapi-starter

By usagerail

•Updated 6 days ago

FastAPI app with API keys, per-customer rate limits, quotas and usage billing via UsageRail

Image
0

205

usagerail/fastapi-starter repository overview

⁠FastAPI + UsageRail starter

A small FastAPI app that already checks API keys. Each request to /v1/* needs a key your customer created, is held to that customer's rate limit and quota, and is counted for usage billing. /health answers without a key.

The checks run inside the container, in the UsageRail Python SDK. Requests don't go through a gateway or proxy. The SDK keeps a synced copy of your keys and sends usage totals to UsageRail once a minute, and UsageRail bills your customers through your own Stripe account. The middleware setup and its options are explained on the FastAPI API keys and usage billing⁠ page of the docs.

What's in the image:

  • Python 3.13.18 on python:3.13.18-slim-trixie
  • usagerail 0.1.1, fastapi 0.142.2, starlette 1.7.0, uvicorn 0.54.0, every dependency pinned with hashes
  • runs as a non-root user (app, uid 10001) on port 8000
  • a HEALTHCHECK that calls /health
  • linux/amd64 and linux/arm64

⁠Run it

You need an app key. Sign up at app.usagerail.com (the free plan needs no card), choose New app, and pick Test mode, the SDK integration and a key prefix such as acme. The console shows the app key once. It starts with urk_test_.

Keep the key out of your shell history: create a file named usagerail.env in a text editor with one line, USAGERAIL_APP_KEY=urk_test_..., then run:

chmod 600 usagerail.env

docker run -d --name api -p 8000:8000 --env-file usagerail.env usagerail/fastapi-starter:0.1.0

-e USAGERAIL_APP_KEY=urk_test_... works too, but then the key sits in your shell history. Either way, anyone who can run docker inspect on the host can read it.

The image contains no keys. Without USAGERAIL_APP_KEY the container exits at once with:

USAGERAIL_APP_KEY is not set. Create an app at https://app.usagerail.com, copy its app key (urk_test_... or urk_live_...) and pass it with -e USAGERAIL_APP_KEY or --env-file.

⁠Endpoints

RouteKey neededReturnsCounted as
GET /healthno{"status":"ok"}not counted
GET /docs, GET /openapi.jsonnoSwagger UI and the OpenAPI schemanot counted
GET /v1/helloyes{"message":"Hello"}1 request
POST /v1/word-countyes{"words": n} for a body like {"text": "..."}, up to 1,000,000 characters1 request, or n units if your app counts units

Open http://localhost:8000/docs to try the routes in the browser: choose Authorize and paste a customer key.

⁠Try it

In the console, open Customers, add a customer and choose Create key on their page. Below, acme_test_... stands for that key.

curl -i http://localhost:8000/v1/hello -H "Authorization: Bearer acme_test_..."
HTTP/1.1 200 OK
content-type: application/json

{"message":"Hello"}

The key can also go in an X-API-Key header:

curl -i -X POST http://localhost:8000/v1/word-count \
  -H "X-API-Key: acme_test_..." \
  -H "Content-Type: application/json" \
  -d '{"text": "metered APIs bill per unit"}'

That returns {"words":5}. If the app counts units (Settings > What counts as usage), this request counts as 5. If it counts requests, it counts as 1.

Without a key, or with something that isn't a key, the SDK answers before the route runs:

HTTP/1.1 401 Unauthorized
content-type: application/json

{"error": "invalid_api_key"}

A customer over their rate limit gets a 429 with Retry-After and the IETF RateLimit headers. This one came from a plan limited to 1 request per second:

HTTP/1.1 429 Too Many Requests
retry-after: 1
ratelimit-policy: "per_second";q=1;w=1
ratelimit: "per_second";r=0;t=1
content-type: application/json

{"error": "rate_limited", "retry_after": 1}

A quota set to stop at the limit returns 429 quota_exceeded, and a prepaid plan with no credits left returns 402 insufficient_credits. Rejected requests and 4xx/5xx responses are recorded but never billed. Counts show up on the console's Usage page about a minute after the requests.

⁠If the app key is wrong

The container still starts, and /health still answers. The log shows:

UsageRail: sync failed (GET /v1/sync returned 401)

Requests without a key, or with a malformed one, still get the 401. A request with a real-looking customer key gets a 503 {"error": "auth_unavailable"}, because the SDK can't confirm the key with UsageRail. Fix the key in your env file and recreate the container.

⁠Make it your own

The app is one file, /app/main.py. The quickest way to change it is to copy it out, edit it and build on top of this image:

docker create --name tmp usagerail/fastapi-starter:0.1.0
docker cp tmp:/app/main.py .
docker rm tmp
FROM usagerail/fastapi-starter:0.1.0

# Extra packages, if your routes need any
USER root
RUN pip install httpx==0.28.1
USER app

COPY --chown=app:app main.py .

Things to keep when you edit main.py:

  • The UsageRailExceptOpenPaths wrapper. The SDK's FastAPI middleware has no option to skip a route, so the wrapper sends the paths in OPEN_PATHS straight to your app and everything else through UsageRail. Add your webhook receivers there, for example "/webhooks/stripe", and take out /docs and /openapi.json if your API docs shouldn't be public. Paths are compared exactly, so /health/ still asks for a key.
  • Paid routes in the main app. Don't move them into a mounted sub-app. A mounted app gets no lifespan events, and the SDK sends its last counts during lifespan shutdown.
  • request.state.usagerail.track(n) in any route that should bill by units (tokens, words, rows). Use a whole number from 0 to 10,000,000. Anything else is ignored with a warning in the log, and the request counts as 1, so cap your inputs the way /v1/word-count does. track() does nothing while the app counts requests.

If your API already has its own keys or logins, switch to auth="custom" with a consumer function. That setup, the on_reject hook for your own error body, and the settings for when UsageRail can't be reached are covered in the FastAPI docs linked above.

⁠Running it for real

  • Use a live app key (urk_live_...) only after you've tested with a test app. Test and live are separate apps, each with its own customers and keys.
  • The SDK sends counts every 60 seconds and once more when uvicorn shuts down. docker stop sends SIGTERM and waits 10 seconds before killing the container, which is normally plenty. If the container is killed outright (docker kill, out of memory), the counts it hadn't sent are lost and never billed.
  • The SDK saves its synced key list in the container's temp directory, so a restarted process doesn't wait for the first sync. A new container starts without it and syncs within a few seconds.
  • Rate limits are counted per container by default. With three replicas behind a load balancer, a customer limited to 10 requests per second can get up to 30. The app's settings have a mode that divides the limit by the number of running instances.
  • The image runs one uvicorn worker. For more, scale out with more containers, or override the command, e.g. uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4. Each worker is its own SDK instance, so per-instance rate limits apply per worker.

⁠Source and license

The SDK is MIT-licensed. Its source, along with the Node.js SDK, is at https://github.com/usagerail/sdk⁠.

Tag summary

Content type

Image

Digest

sha256:da0edd167…

Size

46.5 MB

Last updated

6 days ago

docker pull usagerail/fastapi-starter