Litestar
Litestar is a production-ready, highly performant, and extensible ASGI API framework, currently at version 2.21.1. It emphasizes type safety, developer experience, and modularity, supporting features like dependency injection, OpenAPI schema generation, and ORM integration. The project maintains a frequent release cadence, often issuing minor versions monthly or bi-weekly.
Warnings
- breaking Project Rebranding (Starlite to Litestar): With the release of v2.0, the framework was renamed from 'Starlite' to 'Litestar'. All import paths must be updated accordingly (e.g., `from starlite import ...` becomes `from litestar import ...`).
- breaking Pydantic Integration Changes: Pydantic was removed from Litestar's core in v2.0, making it an optional dependency. While Pydantic models are still fully supported via a plugin, the framework's internal data handling switched to `msgspec` for performance. If you were implicitly relying on Pydantic for non-Pydantic types, behavior might differ.
- breaking Middleware API Evolution: The `MiddlewareProtocol` and `AbstractMiddleware` classes were deprecated around v2.15 in favor of the `ASGIMiddleware` abstract base class. This change simplifies middleware configuration and dispatching.
- gotcha Strict Type Hinting Enforcement: Litestar rigorously uses and enforces Python type hints for data validation, parsing, serialization, and OpenAPI schema generation. Failing to provide accurate type hints (e.g., return types for route handlers) can lead to runtime exceptions.
- gotcha Event Loop Management in Async Tests: When using `httpx.AsyncClient` or the synchronous `TestClient` with async testing frameworks like `pytest-asyncio`, running the Litestar application in a different event loop than the test/fixture can lead to `RuntimeError: Event loop is closed`. This is a common pitfall in async Python testing.
- gotcha Exception Handler Scope for 404/405 Errors: `NotFoundException` (404) and `MethodNotAllowedException` (405) are raised by Litestar's ASGI Router before the middleware stack is fully invoked. Consequently, these exceptions can only be handled by exception handlers registered directly on the `Litestar` application instance, not by handlers defined on specific controllers or route handlers.
Install
-
pip install 'litestar[standard]'
Imports
- Litestar
from litestar import Litestar
- get
from litestar import get
- post
from litestar import post
- Controller
from litestar import Controller
- ASGIMiddleware
from litestar.middleware import ASGIMiddleware
- AsyncTestClient
from litestar.testing import AsyncTestClient
- ASGIConnection
from litestar.connection import ASGIConnection
Quickstart
from litestar import Litestar, get
import os
@get("/")
async def hello_world() -> str:
return f"Hello, {os.environ.get('NAME', 'World')}!"
app = Litestar(route_handlers=[hello_world])
# To run this application:
# 1. Save it as app.py
# 2. Run in terminal: litestar run --reload
# 3. Access at http://127.0.0.1:8000/