Add UsageRail to an API
БесплатноБез исполняемых скриптовНе проверенAdd API keys, per-customer rate limits, quotas and usage metering to a Node.js or Python API server with the UsageRail SDK. Use when someone wants to sell…
от supertj239 установок в других каталогахОб этом скилле
Add UsageRail to an API
UsageRail's SDK checks API keys, applies rate limits and quotas, and counts usage per customer inside the user's own API server. Requests never pass through UsageRail. Counts go to UsageRail in the background every 60 seconds.
Before you change anything
- Find the framework. The SDKs cover Express, Hono, Fastify and Next.js on Node.js 22+, and FastAPI, Starlette, Flask and Django on Python 3.10+. For other languages, use the HTTP check endpoint described at https://usagerail.com/docs. It adds one network call per request.
- Ask how callers authenticate today. With no keys yet, use
auth: "api-key"and UsageRail issues the keys. With existing keys or logins, useauth: "custom"with aconsumerfunction. In Node.js it returns{ id }for the caller, ornullfor anonymous traffic. In Python it returns the customer's ID as a string, orNone. A bare string returned in Node.js is counted as anonymous. Return an identity the app's own code has verified, never a value the caller can set, such as a plain header. UsageRail has to run after that authentication: in Express,app.use(usageRail(...))goes after the auth middleware. In FastAPI the identity must come from an authentication middleware, notDepends(...), and since FastAPI runs the middleware added last first, add the auth middleware after the line that adds UsageRail. In Django, list UsageRail afterAuthenticationMiddleware. Django REST framework token or JWT authentication runs inside the view, after all middleware, so a consumer that readsrequest.usersees anonymous traffic: verify the token in the consumer function or in an earlier middleware. In Flask, register the app's ownbefore_requesthook first. - The user needs an app key from https://app.usagerail.com. Read it from the
USAGERAIL_APP_KEYenvironment variable. Never write the key into source code, and never ask the user to paste it into the chat.
Wire it in
Every request counts as 1 by default. The track() calls below only change that once the app counts units, which is set in the console under Settings > What counts as usage. While the app counts requests, track() does nothing.
FastAPI or Starlette
pip install usagerail
import os
from fastapi import FastAPI, Request
from usagerail.fastapi import UsageRailMiddleware
app = FastAPI()
app.add_middleware(UsageRailMiddleware, app_key=os.environ["USAGERAIL_APP_KEY"], auth="api-key")
@app.post("/v1/generate")
async def generate(request: Request):
result = await run_model(await request.json())
request.state.usagerail.track(result.tokens) # optional: count tokens instead of requests
return result.body
Flask
import os
from flask import Flask
from usagerail.flask import UsageRail
app = Flask(__name__)
UsageRail(app, app_key=os.environ["USAGERAIL_APP_KEY"], auth="api-key")
Inside a route, g.usagerail.track(n) counts custom units.
Django
# settings.py
import os
MIDDLEWARE = [
# ...
"usagerail.django.UsageRailMiddleware",
]
USAGERAIL = {"app_key": os.environ["USAGERAIL_APP_KEY"], "auth": "api-key"}
Inside a view, request.usagerail.track(n) counts custom units.
Under uvicorn or another ASGI server, wrap the application in asgi.py, or every restart loses the counts that hadn't gone out yet:
import os
from django.core.asgi import get_asgi_application
from usagerail.django import asgi
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
application = asgi(get_asgi_application())
Express
npm install @usagerail/node
import express from "express";
import { usageRail } from "@usagerail/node/express";
const app = express();
app.use(usageRail({
appKey: process.env.USAGERAIL_APP_KEY,
auth: "api-key",
}));
app.post("/v1/generate", express.json(), async (req, res) => {
const result = await generate(req.body);
req.usageRail.track(result.tokens); // optional: count tokens
res.json(result);
});
Hono and Fastify have their own entry points: @usagerail/node/hono and @usagerail/node/fastify. Hono on Node.js doesn't flush on its own: also call flushOnExit(rail.engine) from @usagerail/node/node, or counts not yet sent are lost when the process stops. Follow the framework's page in the docs for the full setup.
On SIGTERM the Express middleware sends what's left, waiting at most 5 seconds, then lets the process exit. If the app handles SIGTERM itself, keep the value usageRail() returned and finish the app's own shutdown with await middleware.engine.close().
How callers send their key
In the Authorization: Bearer <key> header, or in x-api-key when there's no bearer token.
What rejected requests look like
| Status | Meaning |
|---|---|
| 401 | Unknown or revoked key |
| 402 | Prepaid credit used up |
| 403 | Suspended customer |
| 429 | Rate limit or quota reached |
| 503 | UsageRail unreachable, and the app is set |
Установить Add UsageRail to an API в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Add UsageRail to an API?
Add API keys, per-customer rate limits, quotas and usage metering to a Node.js or Python API server with the UsageRail SDK. Use when someone wants to sell access to their API, charge by usage through their own Stripe account, or keep one customer from using up their API.
Как установить скилл Add UsageRail to an API?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Add UsageRail to an API запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic