Your First Endpoint (with Validation)
Build a JSON endpoint and validate its input so bad requests fail cleanly with field-level errors.
An endpoint
from larz import Larz
import larz.api as api
app = Larz(secret="...")
api.enable(app)
@app.post("/api/wordcount")
def wordcount(req):
return {"words": len(req.json()["text"].split())}Validate the input
Never trust the caller. A schema rejects bad requests with a 400 and field-level errors before your code runs.
@app.validate({"text": {"type": str, "required": True, "maxlen": 5000}})
@app.post("/api/wordcount")
def wordcount(req):
return {"words": len(req.data["text"].split())} # req.data is validatedTakeaways
- Return a dict and Larz serializes JSON automatically.
@app.validate(schema)guards type/required/min/max/maxlen/choices.- Validated input lands on
req.data.