DocumentationRoutes and routers
API referenceGitHub

Routes and routers

Organize endpoints with app decorators, reusable routers, prefixes, tags, and all common HTTP verbs.

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

01

Register a route on the app

Use route decorators directly on LENAPI for a small API. Typed values that are not in the path are query parameters; values whose names appear in the path are path parameters. LenAPI includes both in the OpenAPI document, where you can try them in Swagger UI.

Python
from lenapi import LENAPI

app = LENAPI()

# item_id is a query parameter: GET /items/?item_id=12
@app.get("/items/")
def get_item(item_id: int):
    return {"item_id": item_id}

# item_id is a path parameter: GET /items/12
@app.get("/items/{item_id}")
def get_item_by_id(item_id: int):
    return {"item_id": item_id}
02

Define the request schema in the app

Keep Pydantic request and response models in the generated app/schemas.py module. Import Greeting in the route module; LenAPI uses that annotation to validate the JSON body and publish the Greeting fields in Swagger.

Python
# app/schemas.py
from pydantic import BaseModel

class Greeting(BaseModel):
    name: str
03

Group endpoints with a Router

Routers let you keep related endpoints together. The router prefix is prepended to each route path. Import the request schema from app.schemas so Swagger can display its request body for this endpoint.

Python
# main.py
from lenapi import LENAPI, Router
from app.schemas import Greeting

app = LENAPI()
api = Router(prefix="/api", tag_name="Greeting")

@api.post("/hello")
async def hello(data: Greeting):
    return {"message": f"Hello, {data.name}!"}

app.include_router(api)
TIP

This registers POST /api/hello. In /docs/, Swagger shows the Greeting request schema and lets you send a JSON body such as {"name": "Ada"}.

04

Choose the HTTP method and organize Swagger tags

Use GET to read, POST to create, PUT to replace, PATCH to partially update, and DELETE to remove a resource. A router tag supplies the default group in Swagger. A tag on include_router can set the group for mounted routes, while a route tag lets you label an individual operation.

Python
@api.patch("/users/{user_id}", tag_name="User edits")
def patch_user(user_id: int, data: UserPatch):
    return {"id": user_id, "updated": True}

# The mount tag is used to group the router's endpoints in Swagger.
app.include_router(api, tag_name="Public API")
TIP

Use PATCH for partial updates and PUT when the request replaces the resource representation. You can include multiple routers on one app, each with its own prefix and Swagger tag.