or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

application-routing.mdconfiguration.mddto.mdexceptions.mdhttp-handlers.mdindex.mdmiddleware.mdopenapi.mdplugins.mdrequest-response.mdsecurity.mdtesting.mdwebsocket.md
tile.json

tessl/pypi-litestar

Litestar is a powerful, flexible yet opinionated ASGI web framework specifically focused on building high-performance APIs.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/litestar@2.17.x

To install, run

npx @tessl/cli install tessl/pypi-litestar@2.17.0

index.mddocs/

Litestar

Litestar is a powerful, flexible yet opinionated ASGI web framework specifically focused on building high-performance APIs. It provides comprehensive features including high-performance data validation, dependency injection system, first-class ORM integration, authorization primitives, rich plugin API, and middleware support.

Package Information

  • Package Name: litestar
  • Language: Python
  • Installation: pip install litestar

Core Imports

from litestar import Litestar

For building applications:

from litestar import Litestar, get, post, put, delete, patch
from litestar import Request, Response
from litestar import Controller, Router

Basic Usage

from litestar import Litestar, get

@get("/")
def hello_world() -> dict[str, str]:
    return {"hello": "world"}

@get("/users/{user_id:int}")
def get_user(user_id: int) -> dict[str, int]:
    return {"user_id": user_id}

app = Litestar(route_handlers=[hello_world, get_user])

# Run with uvicorn app:app

Architecture

Litestar follows a layered architecture built on ASGI:

  • Application (Litestar): The main ASGI application that manages routing, middleware, and configuration
  • Routing: Router and Controller classes organize route handlers with path prefixes and shared configuration
  • Handlers: Route handler functions/methods decorated with HTTP method decorators (get, post, etc.)
  • Middleware: Request/response processing pipeline with authentication, CORS, compression, etc.
  • Connection Objects: Request and WebSocket objects provide access to ASGI scope, headers, body, etc.
  • Response Objects: Structured response objects for different content types (JSON, files, templates, etc.)
  • Dependency Injection: Powerful DI system for managing dependencies across handlers
  • Plugins: Extensible plugin system for integrating with external libraries

Capabilities

Application and Routing

Core application setup, routing configuration, and request handling. Includes the main Litestar application class, routers for organizing routes, and controllers for OOP-style route organization.

class Litestar:
    def __init__(
        self,
        route_handlers: Sequence[ControllerRouterHandler] | None = None,
        *,
        middleware: Sequence[Middleware] | None = None,
        dependencies: Dependencies | None = None,
        exception_handlers: ExceptionHandlersMap | None = None,
        # ... many more configuration options
    ): ...

class Router:
    def __init__(
        self,
        path: str = "",
        route_handlers: Sequence[ControllerRouterHandler] | None = None,
        *,
        dependencies: Dependencies | None = None,
        middleware: Sequence[Middleware] | None = None,
        # ... more options
    ): ...

class Controller:
    path: str = ""
    dependencies: Dependencies | None = None
    middleware: Sequence[Middleware] | None = None
    # ... controller configuration

Application and Routing

HTTP Route Handlers

Decorators and classes for handling HTTP requests including GET, POST, PUT, DELETE, PATCH, and generic route handlers. Supports path parameters, query parameters, request body parsing, and response generation.

def get(
    path: str | Sequence[str] | None = None,
    *,
    dependencies: Dependencies | None = None,
    middleware: Sequence[Middleware] | None = None,
    name: str | None = None,
    # ... more options
) -> Callable[[AnyCallable], HTTPRouteHandler]: ...

def post(path: str | Sequence[str] | None = None, **kwargs) -> Callable: ...
def put(path: str | Sequence[str] | None = None, **kwargs) -> Callable: ...
def patch(path: str | Sequence[str] | None = None, **kwargs) -> Callable: ...
def delete(path: str | Sequence[str] | None = None, **kwargs) -> Callable: ...

HTTP Route Handlers

Request and Response Objects

Connection objects for accessing request data including headers, body, query parameters, and path parameters. Response objects for returning different content types and status codes.

class Request(ASGIConnection):
    async def json(self) -> Any: ...
    async def body(self) -> bytes: ...
    async def form(self) -> dict[str, Any]: ...
    def query_params(self) -> dict[str, Any]: ...
    def path_params(self) -> dict[str, Any]: ...
    def headers(self) -> Headers: ...
    def cookies(self) -> dict[str, str]: ...

class Response:
    def __init__(
        self,
        content: Any = None,
        *,
        status_code: int = 200,
        headers: ResponseHeaders | None = None,
        media_type: MediaType | str | None = None,
        # ... more options
    ): ...

Request and Response

WebSocket Support

WebSocket connection handling with decorators for WebSocket routes, listeners, and streaming. Supports real-time bidirectional communication between client and server.

def websocket(
    path: str | Sequence[str] | None = None,
    *,
    dependencies: Dependencies | None = None,
    middleware: Sequence[Middleware] | None = None,
    # ... more options
) -> Callable: ...

def websocket_listener(
    path: str | Sequence[str] | None = None,
    **kwargs
) -> Callable: ...

class WebSocket(ASGIConnection):
    async def accept(self, subprotocols: str | None = None) -> None: ...
    async def send_text(self, data: str) -> None: ...
    async def send_bytes(self, data: bytes) -> None: ...
    async def send_json(self, data: Any) -> None: ...
    async def receive_text(self) -> str: ...
    async def receive_bytes(self) -> bytes: ...
    async def receive_json(self) -> Any: ...
    async def close(self, code: int = 1000, reason: str | None = None) -> None: ...

WebSocket Support

Middleware System

Middleware components for request/response processing including authentication, CORS, compression, rate limiting, and custom middleware. Supports both function-based and class-based middleware.

class AbstractMiddleware:
    def __init__(self, app: ASGIApp): ...
    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: ...

def DefineMiddleware(
    middleware: type[AbstractMiddleware] | Callable,
    *args: Any,
    **kwargs: Any,
) -> DefineMiddleware: ...

class AbstractAuthenticationMiddleware(AbstractMiddleware):
    async def authenticate_request(self, connection: ASGIConnection) -> AuthenticationResult: ...

Middleware

Security and Authentication

Authentication and authorization systems including JWT authentication, session-based auth, and OAuth2 support. Provides security primitives for protecting routes and managing user sessions.

class JWTAuth(BaseJWTAuth):
    def __init__(
        self,
        token_secret: str,
        retrieve_user_handler: UserHandlerProtocol,
        *,
        algorithm: str = "HS256",
        auth_header: str = "Authorization",
        # ... more options
    ): ...

class SessionAuth:
    def __init__(
        self,
        retrieve_user_handler: UserHandlerProtocol,
        session_backend: BaseSessionBackend,
        *,
        exclude: str | list[str] | None = None,
        # ... more options
    ): ...

Security and Authentication

Data Transfer Objects (DTOs)

Serialization and validation system using DTOs for request/response data transformation. Supports dataclasses, Pydantic models, and msgspec structs with automatic validation and conversion.

class AbstractDTO:
    config: DTOConfig

class DataclassDTO(AbstractDTO):
    @classmethod
    def create_for_field_definition(
        cls, field_definition: FieldDefinition, config: DTOConfig | None = None
    ) -> type[AbstractDTO]: ...

class DTOConfig:
    def __init__(
        self,
        *,
        exclude: set[str] | None = None,
        include: set[str] | None = None,
        rename_fields: dict[str, str] | None = None,
        # ... more options
    ): ...

Data Transfer Objects

Exception Handling

Framework-specific exceptions and error handling including HTTP exceptions, validation errors, and custom exception handlers. Provides structured error responses and debugging support.

class HTTPException(Exception):
    def __init__(
        self,
        detail: str = "",
        *,
        status_code: int = 500,
        headers: dict[str, str] | None = None,
        extra: dict[str, Any] | None = None,
    ): ...

class ValidationException(HTTPException): ...
class NotAuthorizedException(HTTPException): ...
class PermissionDeniedException(HTTPException): ...
class NotFoundException(HTTPException): ...

Exception Handling

Testing Utilities

Test client implementations for testing Litestar applications. Includes synchronous and asynchronous test clients with support for HTTP requests, WebSocket connections, and integration testing.

class TestClient:
    def __init__(self, app: Litestar, **kwargs): ...
    def get(self, url: str, **kwargs) -> httpx.Response: ...
    def post(self, url: str, **kwargs) -> httpx.Response: ...
    def put(self, url: str, **kwargs) -> httpx.Response: ...
    def delete(self, url: str, **kwargs) -> httpx.Response: ...

class AsyncTestClient:
    def __init__(self, app: Litestar, **kwargs): ...
    async def get(self, url: str, **kwargs) -> httpx.Response: ...
    async def post(self, url: str, **kwargs) -> httpx.Response: ...

Testing

Configuration System

Configuration classes for various framework features including CORS, compression, static files, templates, and application settings. Provides type-safe configuration with validation.

class CORSConfig:
    def __init__(
        self,
        *,
        allow_origins: Sequence[str] | None = None,
        allow_methods: Sequence[str] | None = None,
        allow_headers: Sequence[str] | None = None,
        # ... more options
    ): ...

class CompressionConfig:
    def __init__(
        self,
        backend: Literal["gzip", "brotli"] = "gzip",
        minimum_size: int = 500,
        # ... more options
    ): ...

Configuration

Plugin System

Extensible plugin architecture for integrating with external libraries and extending framework functionality. Includes core plugins and protocols for custom plugin development.

class PluginProtocol(Protocol):
    def on_app_init(self, app_config: AppConfig) -> AppConfig: ...

class SerializationPluginProtocol(PluginProtocol):
    def supports_type(self, field_definition: FieldDefinition) -> bool: ...
    def create_dto_for_type(self, field_definition: FieldDefinition) -> type[AbstractDTO]: ...

Plugins

OpenAPI Documentation

Automatic OpenAPI 3.1 specification generation with customizable documentation, schemas, and interactive API exploration. Supports custom response specifications and parameter documentation.

class OpenAPIConfig:
    def __init__(
        self,
        *,
        title: str = "Litestar API",
        version: str = "1.0.0",
        description: str | None = None,
        servers: list[Server] | None = None,
        # ... more options
    ): ...

class OpenAPIController(Controller):
    path: str = "/schema"

OpenAPI Documentation

Types

Core types used throughout the framework:

# HTTP Methods
class HttpMethod(str, Enum):
    GET = "GET"
    POST = "POST"
    PUT = "PUT"
    PATCH = "PATCH"
    DELETE = "DELETE"
    HEAD = "HEAD"
    OPTIONS = "OPTIONS"
    TRACE = "TRACE"

# Media Types
class MediaType(str, Enum):
    JSON = "application/json"
    HTML = "text/html"
    TEXT = "text/plain"
    XML = "application/xml"
    # ... more media types

# Handler types
ControllerRouterHandler = Controller | Router | BaseRouteHandler
Middleware = Callable | DefineMiddleware | type[AbstractMiddleware]
Dependencies = dict[str, Provide]
ExceptionHandlersMap = dict[type[Exception], ExceptionHandler]