Typed params & dependency injection

Annotate a handler's parameters; Larz validates, coerces and injects them.

class=kw>from larz class=kw>import Depends, Query

@app.post("/items")
class=kw>def create(req, name: str, qty: int = 1, active: bool = True):
    class=kw>return {"name": name, "qty": qty}     class=com># coerced class=kw>from body/form; missing name -> 422

Values are pulled from the JSON body or form (for POST/PUT/PATCH) or the query string (for GET), coerced to the annotation, and injected. A parameter with no default is required; a missing or badly-typed value yields a 422 with a per-field error map.

Dataclass bodies

class=kw>from dataclasses class=kw>import dataclass
@dataclass
class Order:
    product: str
    price: float
    qty: int = 1

@app.post("/order")
class=kw>def order(req, o: Order):                  class=com># the whole JSON body -> a validated Order
    class=kw>return {"total": o.price * o.qty}

Explicit sources

Query, Path, Body and Form markers set where a value comes from and its default: tag: str = Query(None).

Dependency injection

class=kw>def current_user(req):
    class=kw>return db.get(req.session.get("user"))

@app.get("/me")
class=kw>def me(req, user=Depends(current_user)):   class=com># resolved once & cached per request
    class=kw>return user.email

A dependency is any callable; if it takes an argument it receives the request. Handlers that take only req are unaffected โ€” binding is opt-in. Guides: typed validation ยท dependency injection.