Deploy FastAPI Metered API
FastAPI app with API keys, rate limits and per-customer usage counts
railway-fastapi-starter
Just deployed
Deploy and Host FastAPI Metered API on Railway
FastAPI Metered API is a small FastAPI app where every request needs an API key. The UsageRail Python SDK runs inside the app and checks the key, applies each customer's rate limit and quota, and counts usage per customer and per route. There is no gateway in front of it.
About Hosting FastAPI Metered API
The template deploys one service: uvicorn serving the app on the port in PORT. It needs one variable, USAGERAIL_APP_KEY, which you get by creating an app in the UsageRail console (steps at https://usagerail.com/docs/quickstart). Without it the app exits at startup with a message saying so. The SDK syncs keys and limits every 15 seconds and sends usage counts every 60 seconds. It also tries a final report when uvicorn shuts down gracefully, as on a redeploy; a forced stop can lose counts it hadn't sent. Customers, keys and plans are managed in the console, not in this repo.
Common Use Cases
- Starting a paid API in Python and handing out keys to the first customers
- Putting per-customer rate limits and quotas on an existing FastAPI service
- Counting units such as words, rows or tokens instead of requests, for usage billing through your own Stripe account
Dependencies for FastAPI Metered API Hosting
- A UsageRail app key. There's a free plan; limits are on https://usagerail.com/pricing
- Python 3.12 with
usagerail,fastapianduvicorn, pinned inrequirements.txt
Implementation Details
The middleware is added once, and the routes stay plain FastAPI:
from usagerail.fastapi import UsageRailMiddleware
app.add_middleware(UsageRailMiddleware, app_key=app_key, auth="api-key")
POST /v1/word-count shows unit counting with request.state.usagerail.track(words). Calls take the key as Authorization: Bearer or X-API-Key: . Middleware options are covered at https://usagerail.com/docs/fastapi.
Why Deploy FastAPI Metered API on Railway?
This template runs the app as one Railway service with a public domain already set up. Set USAGERAIL_APP_KEY in Variables and it starts. With autodeploy on for your fork's branch, pushes redeploy it, and the SDK tries to send its remaining counts while the old instance shuts down.
Template Content
railway-fastapi-starter
usagerail/railway-fastapi-starterUSAGERAIL_APP_KEY
App key from the UsageRail console (starts with urk_test_ or urk_live_). Steps: https://usagerail.com/docs/quickstart