DocumentationDependencies and shared logic
API referenceGitHub

Dependencies and shared logic

Reuse route logic for authentication, database access, and request-scoped services.

Work through each step in order. The examples use the generated LenAPI project structure and are designed to be adapted to your app.

01

Create a dependency

A dependency is a normal sync or async callable. Its typed inputs are resolved like endpoint parameters. If a dependency and route both declare user_id, LenAPI passes the matching path value into the dependency, then injects its return value into the route parameter.

Python
from lenapi import Depends, LENAPI

app = LENAPI()

def current_user(user_id: int):
    return {"id": user_id, "name": "Tolu"}

@app.post("/profile/{user_id}")
def profile(user_id: int, user: dict = Depends(current_user)):
    return user
TIP

For POST /profile/12, current_user receives user_id=12 and profile receives the dependency result as user. This example demonstrates injection; replace it with real authentication and authorization logic before using it to protect data.

02

Reuse an authenticator

Use Depends for identity in a handler, or pass auth= to enforce authentication at route dispatch and include its security scheme in OpenAPI.

Python
from lenapi import Depends, LENAPI, Router, authentication

app = LENAPI()
authenticate = authentication("jwt", app=app)
api = Router(prefix="/api")

@api.get("/profile", auth=authenticate)
def profile(user=Depends(authenticate)):
    return {"user": user}

app.include_router(api)
TIP

Dependencies are cached within one request. Sync dependencies run off the event loop so blocking callback code does not stall async routes.