Routes

Routes are the access points to the application. In Lila, routes are defined in the routes directory (by default, but you can place them wherever you want) and imported into main.py for use. Routes can be configured to handle HTTP requests, API methods, and more.

In addition to JSONResponse you can use HTMLResponse, RedirectResponse and PlainTextResponse, or StreamingResponse, to transmit data in real-time (useful for streaming video/audio or large responses).

routes/api.py

# Import from lila.core JSONResponse.
from lila.core.responses import JSONResponse
from lila.core.request import Request

# Manages routes for API endpoints.
from lila.core.routing import Router
# Initializes the router instance to handle API app.routes.
router = Router()

# Defines a simple API route that supports the GET method.
@router.route(path='/api', methods=['GET'])
async def api(request: Request):
    """Api function"""
    # Returns a simple JSON response for API verification.
    return JSONResponse({'api': True})
            

Get URL Parameters

In this function, we receive a parameter via the URL using {param}. If the parameter is not provided, it defaults to 'default'. The response is a JSON containing the received value.

Receiving GET Parameters

@router.route(path='/url_with_param/{param}', methods=['GET']) 
async def param(request: Request):  
    param = request.path_params.get('param', 'default') 
    return JSONResponse({"received_param": param})
            

Or you can also do it like this:

Receiving GET Query Parameters
 
@router.route(path='/url_with_query', methods=['GET','POST']) 
async def query_param(request: Request):  
    query_param = request.query_params.get('query_param', 'default_value')
    return JSONResponse({"received_param": query_param})
            

Typed Parameters & HTTP 422

Lila casts path and query values from the handler annotations. Invalid values (for example /items/abc for an int) and missing required query parameters return HTTP 422 with a JSON error list instead of a 500.

Typed Path and Query Parameters

from typing import Optional
from lila.core.routing import Router
from lila.core.request import Request

router = Router(prefix="/api")

@router.get("/items/{id:int}")
async def item(
    request: Request,
    id: int,                     # /items/abc -> 422
    page: int = 1,               # optional with a default
    tag: Optional[int] = None,   # Optional[int] works
    ids: list[int] = [],         # repeat: ?ids=1&ids=2
    q: str | None = None,
):
    return {"id": id, "page": page, "tag": tag, "ids": ids, "q": q}

@router.get("/search")
async def search(request: Request, term: str):
    # term is required: /search without ?term= returns 422
    return {"term": term}
            
Opt-in XSS Sanitization
 
from pydantic import BaseModel
from lila.core.routing import Router

router = Router()

class Comment(BaseModel):
    text: str

# Sanitization is OPT-IN: pass sanitize_xss=True to strip script tags,
# javascript: URLs and inline event handlers before your handler runs.
@router.post('/comments', model=Comment, sanitize_xss=True)
async def create_comment(request: Request, data: Comment):
    # request.state.data holds the validated + sanitized model
    return {"text": data.text}
            
Basic Imports

from lila.core.responses import JSONResponse  # Simplifies sending JSON responses.
from lila.core.routing import Router  # Manages API app.routes.
from lila.core.request import Request  # Handles HTTP requests in the application.
from pydantic import EmailStr, BaseModel  # Validates and parses data models for input validation.
from lila.core.middleware import validate_token

router = Router()
            

️ Middleware and Decorators Usage

Middlewares allow intercepting requests before they reach the main logic of the API. In this example, we use @validate_token to validate a JWT token in the request header.

Middleware Validation

@router.route(path='/api/token', methods=['GET','POST'])
@validate_token  # Middleware to validate JWT token.
async def api_token(request: Request):
    return JSONResponse({'api': True})
            

️ Router-Level Middleware Inheritance

You can apply one or more middlewares directly to a Router instance during initialization. When you do this, every route registered on that router will automatically inherit and execute those middlewares in the exact sequence they are defined (left-to-right).

This pattern is perfect for creating dedicated authentication groups, admin-only sections, rate-limited zones, or custom logging areas without having to manually apply decorators to every single endpoint.

Applying Middlewares to Router

from lila.core.routing import Router
from lila.core.middleware import login_required, validate_token
from lila.core.request import Request
from lila.core.responses import JSONResponse

# All routes registered on this router will require the login session first,
# then they will validate the JWT token.
auth_router = Router(prefix="/api", middlewares=[login_required, validate_token])

# This route automatically inherits and executes both middlewares first!
@auth_router.get("/profile")
async def get_profile(request: Request):
    # If the execution reaches here, the user is guaranteed to be authenticated.
    return JSONResponse({"profile": "User Profile Data"})
            

️ Creating Custom Route Middlewares

Creating custom route middlewares in Lila is clean and effortless thanks to the built-in create_decorator helper from lila.core.middleware. Instead of writing boilerplate decorator wrappers manually with functools.wraps, you simply define an async logic function decorated with @create_decorator.

If your logic function returns a response (like a JSONResponse or redirect), Lila breaks the chain early and returns that response. If it returns True or None, execution continues to the route handler. It automatically supports both unparenthesized usage (@check_admin) and parameterized usage (@check_admin(role="superadmin")).

Creating a Custom Middleware with create_decorator

from lila.core.middleware import create_decorator
from lila.core.request import Request
from lila.core.responses import JSONResponse

@create_decorator
async def check_admin(request: Request, role="admin"):
    # If the logic returns a response, it breaks the chain and returns it.
    # If it returns True or None, execution continues to the route handler.
    user = getattr(request.state, "user", {})
    if user.get("role") != role:
        return JSONResponse({"error": "Unauthorized", "message": f"{role} role required"}, status_code=403)
    return True

# Usage in routes:
# @check_admin                       -> uses default role="admin"
# @check_admin(role="superadmin")    -> uses custom role
@router.get("/admin-panel")
@check_admin
async def admin_panel(request: Request):
    return JSONResponse({"status": "welcome admin"})

@router.get("/superadmin-panel")
@check_admin(role="superadmin")
async def superadmin_panel(request: Request):
    return JSONResponse({"status": "welcome superadmin"})
            

Data Validation with Pydantic

Pydantic allows defining data models that automatically validate user input. Additionally, specifying a model in the route generates automatic documentation in /docs.

Validation with Pydantic

from pydantic import EmailStr, BaseModel
from lila.core.responses import JSONResponse

class ExampleModel(BaseModel):
    email: EmailStr  # Ensures a valid email.
    password: str  # String for password.

# Method 1: Inject via Model Parameter
@router.post('/api/example')
async def login(request: Request, body: ExampleModel):
    # Validation is completely automatic!
    # Validated body is directly passed as an argument.
    return JSONResponse({"email": body.email, "status": "validated"})

# Method 2: Inject via route decorator parameter
@router.route(path='/api/example2', methods=['POST'], model=ExampleModel)
async def login_legacy(request: Request):
    # Validated data is injected into request.state.data
    user_data = request.state.data
    return JSONResponse({"email": user_data.email, "status": "validated"})
            

Automatic Documentation Generation

OpenAPI is mounted by the application, not by the router. With App(openapi=True) (the default) Lila serves the generated schema at /openapi.json and the Swagger UI at /docs. Routes registered on a Router(openapi=False) are omitted from the schema.

Documentation Generation

from lila.core.app import App
from app.routes.api.users import router as users_router

# /openapi.json  -> OpenAPI 3.0 schema
# /docs          -> Swagger UI reading /openapi.json
app = App(routes=[users_router], openapi=True)
            

Importing Routes in main.py

Pass routers (or raw route lists) to App(routes=[...]), or add them later with app.include_router(router, prefix="/api"). router.get_routes() returns the Starlette route objects if you need to merge them manually.

Route Import

from lila.core.app import App
from app.routes.web.index import router as web_router
from app.routes.api.users import router as users_router

app = App(routes=[web_router, users_router])

# Optional extra prefix, without mutating the router itself:
app.include_router(users_router, prefix="/v1")

# Raw Starlette route objects:
from app.routes.health import health_routes
app.include_router(health_routes)   # list of starlette Route objects
            

Performance: Route Caching

Lila can cache GET responses. Caching is opt-in: set cache= (seconds) on a route or default_cache_ttl= on a router. The cache key includes a SHA-256 fingerprint of the request cookies and Authorization header, so authenticated pages never leak into another visitor's cache.

Caching Configuration

# Cache every GET route on this router for 60 seconds.
router = Router(default_cache_ttl=60)

# Route-specific cache (5 minutes). Per-identity by default.
@router.get("/heavy-catalog", cache=300)
async def catalog(request: Request):
    return {"data": "catalog items"}

# Public content only: no identity fingerprint, safe to share.
@router.get("/plans", cache=300, cache_public=True)
async def plans(request: Request):
    return {"plans": ["free", "pro"]}

# No cache: runs on every request.
@router.get("/realtime-feed")
async def feed(request: Request):
    return {"status": "live"}
            

Cached entries live in the configured CACHE_DRIVER (memory by default) and are cleared with Cache.clear() or Cache.clear_async(include_sessions=False).

Honest performance numbers: Lila targets 1–2 worker deployments. Measured on Python 3.14, import lila is about 19 MB RSS (lazy imports; no SQLAlchemy until you use models) and a full App instance is about 42 MB. Route caching and single-flight model queries reduce database load, but always benchmark your own endpoints.

Route Prefixes and HTTP Method Shortcuts

Routes can now have a prefix, which allows grouping multiple endpoints under a common path. Additionally, you can define routes directly with HTTP methods as functions: get, post, put, delete.

routes/api_v2.py

# Initialize the router instance for managing API routes.
router = Router(prefix="/v1/api")

# Define a simple API route that supports GET.
@router.get("/")
async def api(request: Request):
    """Api function"""  # used as the summary in /openapi.json and /docs
    return {"api": True}   # dict -> JSON automatically

# GET and POST on the same path, protected by JWT validation.
@router.route(path="/token", methods=["GET", "POST"])
@validate_token
async def api_token(request: Request):
    """Api Token function"""
    # validate_token sets request.state.jwt and request.state.jwt_user_id
    return {"api": True, "user_id": request.state.jwt_user_id}
        

Using prefixes helps organize your API under a common version path (e.g., v1/api), while method-specific decorators (@router.get, @router.post, etc.) make route definitions cleaner and more intuitive.

HTTP Method Examples with Prefix and Pydantic Models

Routes now support the HTTP methods get, post, put, and delete directly. You can also attach Pydantic models for automatic input validation and documentation generation.

routes/v1_api_example.py

from lila.core.responses import JSONResponse
from lila.core.routing import Router
from lila.core.request import Request
from pydantic import BaseModel

router = Router(prefix="/v1/api")

# ---------------- GET Example ----------------
@router.get("/items/{item_id:int}")
async def get_item(request: Request, item_id: int):
    """Fetch an item by ID. Non-integer IDs return 422."""
    return {"item_id": item_id, "status": "fetched"}

# ---------------- POST Example ----------------
class CreateItemModel(BaseModel):
    name: str
    description: str

@router.post("/items", model=CreateItemModel, csrf=True)
async def create_item(request: Request, data: CreateItemModel):
    """Create a new item. The validated model is also in request.state.data."""
    return {"name": data.name, "description": data.description}

# ---------------- PUT Example ----------------
class UpdateItemModel(BaseModel):
    name: str
    description: str

@router.put("/items/{item_id:int}", model=UpdateItemModel, csrf=True)
async def update_item(request: Request, item_id: int, data: UpdateItemModel):
    """Update an existing item by ID."""
    return {"item_id": item_id, "updated_name": data.name}

# ---------------- DELETE Example ----------------
@router.delete("/items/{item_id:int}")
async def delete_item(request: Request, item_id: int):
    """Delete an item by ID."""
    return {"item_id": item_id, "status": "deleted"}
        

These examples demonstrate how to:

Documentation is automatically generated at /docs and /openapi.json.

️ Manual Validation with RequestParser

While assigning a model=ExampleModel to the route automatically validates incoming data and injects it into request.state.data, sometimes you may need more granular control over parsing the request body or query parameters manually.

For these edge cases, Lila provides a built-in RequestParser in the lila.core.controller module. It safely parses and validates the data against a Pydantic model and returns a standardized dictionary with the results.

Manual Parsing Example

from lila.core.controller import RequestParser
from pydantic import BaseModel
from lila.core.responses import JSONResponse

class MyCustomModel(BaseModel):
    username: str
    age: int

parser = RequestParser()

@router.post("/manual-parse")
async def manual_parse_endpoint(request: Request):
    # Parses the JSON body and validates it against MyCustomModel
    result = await parser.parse_body(request, MyCustomModel)
    
    if not result["success"]:
        # Returns standard validation errors
        return JSONResponse({"error": True, "details": result["errors"]}, status_code=400)
    
    # Access the validated Pydantic model
    validated_data = result["data"]
    return JSONResponse({"status": "parsed", "user": validated_data.username})