Tutorial: a paid API
Selling an API by the call is the classic indie product. Here's the whole thing โ keys, metering, validation, docs โ in about 30 lines.
1. Enable the pieces
class=kw>from larz class=kw>import Larz, Response
class=kw>from larz.models class=kw>import connect
class=kw>import larz.money as money, larz.auth as auth, larz.api as api
app = Larz(secret="...")
connect("api.db")
money.enable(app); auth.enable(app); api.enable(app)
app.enable_docs(title="My API", version="1.0") class=com># /openapi.json + /docs
2. Meter an endpoint, gated by an API key
@app.api_key_required(plan="pro")
@app.validate({"text": {"type": str, "required": True, "maxlen": 5000}})
@app.metered("$0.01/call")
@app.post("/api/summarize")
class=kw>def summarize(req):
class=kw>return {"summary": req.data["text"][:120]}
A request with no key gets 401; a wrong plan gets 403; a valid
key with no credit gets 402; a funded key is billed a cent and served. Billing
follows the key, not the browser session.
3. Issue keys and credit them
key = app.auth.issue_api_key(plan="pro") class=com># show once; only a hash is stored
app.money.store.add_credit("apikey:%s" % key_id, 500) class=com># $5 of prepaid credit