Litestar Framework — Core Concepts
What Litestar is
Litestar (formerly Starlite) is an ASGI web framework for Python, first released in 2022. It was created by Na’aman Hirschfeld and a community of contributors who had specific criticisms of FastAPI’s architecture and wanted to build a framework that addressed them.
Litestar sits in the same space as FastAPI: async-first, type-hint-driven, OpenAPI-documented APIs. But it differs in philosophy — Litestar treats the framework as a cohesive system rather than a thin wrapper over Starlette with Pydantic bolted on.
Key differentiators from FastAPI
Dependency injection is first-class. FastAPI uses Depends() as a function parameter default, which is clever but creates issues with type checkers and IDE support. Litestar uses a dedicated Provide system that integrates cleanly with Python’s type system.
Class-based controllers. FastAPI uses function decorators exclusively. Litestar supports both function handlers and class-based controllers:
from litestar import Controller, get, post
class UserController(Controller):
path = "/users"
@get()
async def list_users(self) -> list[User]:
return await db.get_users()
@post()
async def create_user(self, data: UserCreate) -> User:
return await db.create_user(data)
@get("/{user_id:int}")
async def get_user(self, user_id: int) -> User:
return await db.get_user(user_id)
Controllers group related endpoints with shared middleware, guards, and dependencies — a pattern familiar to developers coming from NestJS or ASP.NET.
Layered architecture. In Litestar, middleware, guards, dependencies, and exception handlers can be applied at four levels: app, router, controller, and handler. Each level inherits from its parent and can override.
Built-in features. Litestar includes out of the box:
- OpenAPI documentation (Swagger, ReDoc, Stoplight Elements)
- Rate limiting
- Caching with multiple backends
- CORS, CSRF protection
- Sessions (cookie, server-side)
- Channels (WebSocket pub/sub)
- DTO (Data Transfer Object) support for controlling serialization
The type-driven approach
Like FastAPI, Litestar uses Python type hints to drive behavior. But it goes further:
from litestar import get
from dataclasses import dataclass
@dataclass
class UserQuery:
name: str | None = None
active: bool = True
page: int = 1
@get("/users")
async def list_users(query: UserQuery) -> list[User]:
# query is automatically populated from URL query parameters
return await db.search(
name=query.name,
active=query.active,
page=query.page
)
Litestar supports dataclasses, attrs, msgspec, Pydantic v1, and Pydantic v2 as data models. This flexibility means you’re not locked into Pydantic — if you prefer msgspec for its speed or attrs for its simplicity, Litestar works with them natively.
Guards for authorization
Guards are Litestar’s authorization mechanism — separate from authentication middleware:
from litestar.connection import ASGIConnection
from litestar.handlers import BaseRouteHandler
async def require_admin(connection: ASGIConnection, handler: BaseRouteHandler) -> None:
if not connection.user.is_admin:
raise PermissionDeniedException("Admin access required")
@get("/admin/stats", guards=[require_admin])
async def admin_stats() -> dict:
return await get_system_stats()
Guards run after authentication middleware resolves connection.user, creating a clean separation between “who are you?” (authentication) and “are you allowed to do this?” (authorization).
Performance
Litestar performs competitively with FastAPI. Both sit on top of ASGI and use similar async patterns. The real performance differences come from:
- Startup optimization: Litestar validates and compiles route configuration at startup, catching errors early
- msgspec support: Using msgspec instead of Pydantic for serialization can yield 5-10x faster JSON encoding/decoding
- Request parsing: Litestar lazily parses request components — query params aren’t parsed unless accessed
When to choose Litestar
Choose Litestar when:
- You value cohesive framework design over ecosystem size
- You want class-based controllers for organizing large APIs
- You need built-in rate limiting, caching, or channels
- You prefer dataclasses or msgspec over Pydantic
- You’re building a larger project where layered middleware matters
Choose FastAPI when:
- Ecosystem size and community support matter most
- You need specific third-party integrations that only exist for FastAPI
- Your team already knows FastAPI
- You want the most Stack Overflow answers available
Common misconception
People often think Litestar is “just another FastAPI clone.” While it was inspired by FastAPI’s approach, Litestar has a fundamentally different internal architecture. FastAPI is a layer over Starlette; Litestar implements its own ASGI handling. The code sharing between them is minimal.
The one thing to remember: Litestar is a cohesive, batteries-included Python web framework that combines FastAPI-style type-driven development with class-based controllers, layered architecture, and built-in production features — trading ecosystem size for design consistency.
See Also
- Python Aiohttp Client Understand Aiohttp Client through a practical analogy so your Python decisions become faster and clearer.
- Python Api Client Design Why building your own API client in Python is like creating a TV remote that only has the buttons you actually need.
- Python Api Documentation Swagger Swagger turns your Python API into an interactive playground where anyone can click buttons to try it out — no coding required.
- Python Api Mocking Responses Why testing with fake API responses is like rehearsing a play with stand-ins before the real actors show up.
- Python Api Pagination Clients Why APIs send data in pages, and how Python handles it — like reading a book one chapter at a time instead of swallowing the whole thing.