API Keys & Plans
Issue API keys tied to plans, authenticate requests, and gate premium endpoints โ the foundation of a paid API.
Issue and require keys
import larz.auth as auth; auth.enable(app)
key = app.auth.issue_api_key(plan="pro") # shown once; only a hash is stored
@app.api_key_required(plan="pro")
@app.post("/api/premium")
def premium(req):
return {"plan": req.api_key.plan}No key returns 401; the wrong plan returns 403. The key is the principal for its request, so billing and quotas follow the key, not a browser session.
Tiers
Issue keys on different plans (free, pro) and gate endpoints per plan. Combine with metering (next session) for usage limits.
Takeaways
- Keys are hashed at rest and shown once.
@app.api_key_required(plan=)authenticates and authorizes.- Everything downstream bills the key.