Larz โบ API key authentication in Python
API keys done right, in one line
API key auth sounds simple until you're hashing keys, scoping them to plans, and tying usage to the right principal. Larz builds all of it in.
pip install larz
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/run")
def run(req):
return {"plan": req.api_key.plan}
Secure by default
- Keys are hashed at rest and shown to the user exactly once.
- A missing key returns
401; the wrong plan returns403. - The key becomes the request's principal, so billing and quotas follow the key โ not a browser session.
Keys that bill themselves
Because the key is the principal, add @app.metered("$0.01/call") and each call is
billed to that key's prepaid credit. That's a complete paid API โ see the
free course.
FAQ
Are API keys stored securely?
Yes โ only a hash of each key is stored, and the raw key is shown to the user once at creation.
Can keys be scoped to plans?
Yes. Issue keys on a plan (e.g. free or pro) and gate endpoints with @app.api_key_required(plan=...).