litestar Documentation

Light, flexible and extensible ASGI framework | Built to scale

8,360 stars Python Python 1 file ยท ~11,156 tokens #api#asgi#asyncio#litestar#litestar-api#litestar-framework#msgspec#openapi
RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy litestar on any server, homelab, or cloud container platform.

1-Click Terminal Command
bash (docker run)
docker run -d --name litestar -p 5423:5423 --restart always postgres:latest
Configured Services & Ports
โš™๏ธ postgres
image: postgres:latest
๐Ÿ”Œ Ports: 5423:5432
โš™๏ธ redis
image: redis:latest
๐Ÿ”Œ Ports: 6397:6379
โš™๏ธ valkey
image: valkey/valkey:latest
๐Ÿ”Œ Ports: 6381:6379
โš™๏ธ nginx
image: nginx
๐Ÿ”Œ Ports: 8187:80
docker-compose.yml
yaml (docker-compose.yml)
version: "3"

services:
  postgres:
    image: postgres:latest
    ports:
      - "5423:5432" # use a non-standard port here
    environment:
      POSTGRES_PASSWORD: super-secret
  redis:
    image: redis:latest
    restart: always
    ports:
      - "6397:6379" # use a non-standard port here
  valkey:
    image: valkey/valkey:latest
    restart: always
    ports:
      - "6381:6379" # also a non-standard port
  nginx:
    image: nginx
    ports:
      - "8187:80"
    volumes:
      - ./nginx_test_files:/usr/share/nginx/html:ro

File: README.md


Litestar is a powerful, flexible yet opinionated ASGI framework, focused on
building APIs. It offers high-performance data validation, dependency injection,
first-class ORM integration, authorization primitives, a rich plugin API, middleware,
and much more that's needed to get applications up and running.

Check out the documentation ๐Ÿ“š for a detailed overview of
its features!

Additionally, the Litestar fullstack repository
can give you a good impression how a fully fledged Litestar application may look.

Table of Contents

Installation

shell
pip install litestar

or to include the CLI and a server (uvicorn) for running your application:

shell
pip install 'litestar[standard]'

Quick Start

python title="app.py"
from litestar import Litestar, get

@get("/")
async def hello_world() -> dict[str, str]:
    """Keeping the tradition alive with hello world."""
    return {"hello": "world"}

app = Litestar(route_handlers=[hello_world])

And run it with

bash
litestar run

Core Features

Example Applications

Pre-built Example Apps

  • litestar-hello-world: A bare-minimum application setup. Great
    for testing and POC work.
  • litestar-fullstack: A reference application that contains most of the boilerplate required for a web application.
    It features a Litestar app configured with best practices, SQLAlchemy 2.0 and SAQ, a frontend integrated with Vitejs and Jinja2 templates, Docker, and more. Like all
    Litestar projects, this application is open to contributions, big and small.

Sponsors

Litestar is an open-source project, and we enjoy the support of our sponsors to help fund the exciting
work we do.

A huge thanks to our sponsors:


Check out our sponsors in the docs

If you would like to support the work that we do please consider becoming a sponsor
via Polar.sh (preferred), GitHub or Open Collective.

Also, exclusively with Polar, you can engage in pledge-based sponsorships.

Features

Class-based Controllers

While supporting function-based route handlers, Litestar also supports and promotes python OOP using class based
controllers:

Example for class-based controllers

python title="my_app/controllers/user.py"
from typing import List, Optional
from datetime import datetime

from litestar import Controller, get, post, put, patch, delete
from litestar.dto import DTOData
from pydantic import UUID4

from my_app.models import User, PartialUserDTO


class UserController(Controller):
    path = "/users"

    @post()
    async def create_user(self, data: User) -> User: ...

    @get()
    async def list_users(self) -> List[User]: ...

    @get(path="/{date:int}")
    async def list_new_users(self, date: datetime) -> List[User]: ...

    @patch(path="/{user_id:uuid}", dto=PartialUserDTO)
    async def partial_update_user(
        self, user_id: UUID4, data: DTOData[PartialUserDTO]
    ) -> User: ...

    @put(path="/{user_id:uuid}")
    async def update_user(self, user_id: UUID4, data: User) -> User: ...

    @get(path="/{user_name:str}")
    async def get_user_by_name(self, user_name: str) -> Optional[User]: ...

    @get(path="/{user_id:uuid}")
    async def get_user(self, user_id: UUID4) -> User: ...

    @delete(path="/{user_id:uuid}")
    async def delete_user(self, user_id: UUID4) -> None: ...

Data Parsing, Type Hints, and Msgspec

Litestar is rigorously typed, and it enforces typing. For example, if you forget to type a return value for a route
handler, an exception will be raised. The reason for this is that Litestar uses typing data to generate OpenAPI specs,
as well as to validate and parse data. Thus, typing is essential to the framework.

Furthermore, Litestar allows extending its support using plugins.

Plugin System, ORM support, and DTOs

Litestar has a plugin system that allows the user to extend serialization/deserialization, OpenAPI generation, and other
features.

It ships with a builtin plugin for SQL Alchemy, which allows the user to use SQLAlchemy declarative classes "natively"
i.e., as type parameters that will be serialized/deserialized and to return them as values from route
handlers.

Litestar also supports the programmatic creation of DTOs with a DTOFactory class, which also supports the use of
plugins.

OpenAPI

Litestar has custom logic to generate OpenAPI 3.1.0 schema, include optional generation of examples using the
polyfactory library.

ReDoc, Swagger-UI and Stoplight Elements API Documentation

Litestar serves the documentation from the generated OpenAPI schema with:

All these are available and enabled by default.

Dependency Injection

Litestar has a simple but powerful DI system inspired by pytest. You can define named dependencies - sync or async - at
different levels of the application, and then selective use or overwrite them.

Example for DI

python
from litestar import Litestar, get
from litestar.di import Provide


async def my_dependency() -> str: ...


@get("/")
async def index(injected: str) -> str:
    return injected


app = Litestar([index], dependencies={"injected": Provide(my_dependency)})

Middleware

Litestar supports typical ASGI middleware and ships with middlewares to handle things such as

  • CORS
  • CSRF
  • Rate limiting
  • GZip, Brotli, and Zstd compression
  • Client- and server-side sessions

Route Guards

Litestar has an authorization mechanism called guards, which allows the user to define guard functions at different
level of the application (app, router, controller etc.) and validate the request before hitting the route handler
function.

Example for route guards

python
from litestar import Litestar, get

from litestar.connection import ASGIConnection
from litestar.handlers.base import BaseRouteHandler
from litestar.exceptions import NotAuthorizedException


async def is_authorized(connection: ASGIConnection, handler: BaseRouteHandler) -> None:
    # validate authorization
    # if not authorized, raise NotAuthorizedException
    raise NotAuthorizedException()


@get("/", guards=[is_authorized])
async def index() -> None: ...


app = Litestar([index])

Request Life Cycle Hooks

Litestar supports request life cycle hooks, similarly to Flask - i.e. before_request and after_request

Performance

Litestar is fast. It is on par with, or significantly faster than comparable ASGI frameworks.

You can see and run the benchmarks here,
or read more about it here in our documentation.

Contributing

Litestar is open to contributions big and small. You can always join our discord server
or join our Matrix space
to discuss contributions and project maintenance. For guidelines on how to contribute, please
see the contribution guide.

Contributors โœจ

Thanks goes to these wonderful people:
Emoji Key

Na'aman Hirschfeld๐Ÿšง ๐Ÿ’ป ๐Ÿ“– โš ๏ธ ๐Ÿค” ๐Ÿ’ก ๐Ÿ› Peter Schutt๐Ÿšง ๐Ÿ’ป ๐Ÿ“– โš ๏ธ ๐Ÿค” ๐Ÿ’ก ๐Ÿ› Ashwin Vinod๐Ÿ’ป ๐Ÿ“– Damian๐Ÿ“– Vincent Sarago๐Ÿ’ป Jonas Krรผger Svensson๐Ÿ“ฆ Sondre Lillebรธ Gundersen๐Ÿ“ฆ
Lev๐Ÿ’ป ๐Ÿค” Tim Wedde๐Ÿ’ป Tory Clasen๐Ÿ’ป Arseny Boykov๐Ÿ’ป ๐Ÿค” Jacob Rodgers๐Ÿ’ก Dane Solberg๐Ÿ’ป madlad33๐Ÿ’ป
**Matthew Aylward **๐Ÿ’ป Jan Klima๐Ÿ’ป C2Dโš ๏ธ to-ph๐Ÿ’ป imbev๐Ÿ“– cฤƒtฤƒlin๐Ÿ’ป Seon82๐Ÿ“–
Slava๐Ÿ’ป Harry๐Ÿ’ป ๐Ÿ“– Cody Fincher๐Ÿšง ๐Ÿ’ป ๐Ÿ“– โš ๏ธ ๐Ÿค” ๐Ÿ’ก ๐Ÿ› Christian Clauss๐Ÿ“– josepdaniel๐Ÿ’ป devtud๐Ÿ› Nicholas Ramos๐Ÿ’ป
seladb๐Ÿ“– ๐Ÿ’ป Simon Wienhรถfer๐Ÿ’ป MobiusXS๐Ÿ’ป Aidan Simard๐Ÿ“– wweber๐Ÿ’ป Samuel Colvin๐Ÿ’ป Mateusz Mikoล‚ajczyk๐Ÿ’ป
**Alex **๐Ÿ’ป Odiseo๐Ÿ“– Javier Pinilla๐Ÿ’ป Chaoying๐Ÿ“– infohash๐Ÿ’ป John Ingles๐Ÿ’ป Eugeneโš ๏ธ ๐Ÿ’ป
Jon Daly๐Ÿ“– ๐Ÿ’ป Harshal Laheri๐Ÿ’ป ๐Ÿ“– Tรฉva KRIEF๐Ÿ’ป Konstantin Mikhailov๐Ÿšง ๐Ÿ’ป ๐Ÿ“– โš ๏ธ ๐Ÿค” ๐Ÿ’ก ๐Ÿ› Mitchell Henry๐Ÿ“– chbndrhnns๐Ÿ“– nielsvanhooy๐Ÿ’ป ๐Ÿ› โš ๏ธ
provinzkraut๐Ÿšง ๐Ÿ’ป ๐Ÿ“– โš ๏ธ ๐Ÿค” ๐Ÿ’ก ๐Ÿ› ๐ŸŽจ Joshua Bronson๐Ÿ“– Roman Reznikov๐Ÿ“– mookrs๐Ÿ“– Mike DePalatis๐Ÿ“– Carlos Alberto Pรฉrez-Molano๐Ÿ“– ThinksFastโš ๏ธ ๐Ÿ“–
Christopher Krause๐Ÿ’ป Kyle Smith๐Ÿ’ป ๐Ÿ“– ๐Ÿ› Scott Bradley๐Ÿ› Srikanth Chekuriโš ๏ธ ๐Ÿ“– Michael Bosch๐Ÿ“– sssssss340๐Ÿ› ste-pool๐Ÿ’ป ๐Ÿš‡
Alc-Alc๐Ÿ“– ๐Ÿ’ป โš ๏ธ ๐Ÿš‡ asomethings๐Ÿ’ป Garry Bullock๐Ÿ“– Niclas Haderer๐Ÿ’ป Diego Alvarez๐Ÿ“– ๐Ÿ’ป โš ๏ธ Jason Nance๐Ÿ“– Igor Kapadze๐Ÿ“–
Somraj Saha๐Ÿ“– Magnรบs รgรบst Skรบlason๐Ÿ’ป ๐Ÿ“– Alessio Parma๐Ÿ“– Peter Brunner๐Ÿ’ป Jacob Coffee๐Ÿ“– ๐Ÿ’ป โš ๏ธ ๐Ÿš‡ ๐Ÿค” ๐Ÿšง ๐Ÿ’ผ ๐ŸŽจ Gamazic๐Ÿ’ป Kareem Mahlees๐Ÿ’ป
Abdulhaq Emhemmed๐Ÿ’ป ๐Ÿ“– Jenish๐Ÿ’ป ๐Ÿ“– chris-telemetry๐Ÿ’ป Ward๐Ÿ› Stephan Fitzpatrick๐Ÿ› Eric Kennedy๐Ÿ“– wassaf shahzad๐Ÿ’ป
Nils Olsson๐Ÿ’ป ๐Ÿ› Riley Chase๐Ÿ’ป arl๐Ÿšง Antoine van der Horst๐Ÿ“– Nick Groenen๐Ÿ“– Giorgio Vilardo๐Ÿ“– Nicholas Bollweg๐Ÿ’ป
Tomas Jonssonโš ๏ธ ๐Ÿ’ป Khiem Doan๐Ÿ“– kedod๐Ÿ“– ๐Ÿ’ป โš ๏ธ sonpro1296๐Ÿ’ป โš ๏ธ ๐Ÿš‡ ๐Ÿ“– Patrick Armengol๐Ÿ“– Sander๐Ÿ“– ็–ฏไบบ้™ขไธปไปป๐Ÿ“–
aviral-nayya๐Ÿ’ป whiskeyriver๐Ÿ’ป Phyo Arkar Lwin๐Ÿ’ป MatthewNewland๐Ÿ› ๐Ÿ’ป โš ๏ธ Tom Kuo๐Ÿ› LeckerenSirupwaffeln๐Ÿ› Daniel Gonzรกlez Fernรกndez๐Ÿ“–
01EK98๐Ÿ“– Sarbo Roy๐Ÿ’ป Ryan Seeley๐Ÿ’ป Felix๐Ÿ“– ๐Ÿ› George Sakkis๐Ÿ’ป Huba Tuba๐Ÿ“– ๐Ÿ’ป โš ๏ธ Stefane Fermigier๐Ÿ“–
r4ge๐Ÿ’ป ๐Ÿ“– Jay๐Ÿ’ป sinisaos๐Ÿ“– Tharuka Devendra๐Ÿ’ป euri10๐Ÿ’ป ๐Ÿ“– ๐Ÿ› Shubham๐Ÿ“– Erik Hasse๐Ÿ› ๐Ÿ’ป
Nikita Sobolev๐Ÿš‡ ๐Ÿ’ป Nguyแป…n Hoร ng ฤแปฉc๐Ÿ› RavanaBhrama๐Ÿ“– Marcel Johannesmann๐Ÿ“– Matthew๐Ÿ“– Mattwmaster58๐Ÿ› ๐Ÿ’ป โš ๏ธ Manuel Sanchez Pinar๐Ÿ“–
Juan Riveros๐Ÿ“– David Brochart๐Ÿ“– Sean Donoghue๐Ÿ“– P.C. Shyamshankar๐Ÿ› ๐Ÿ’ป โš ๏ธ William Evonosky๐Ÿ’ป geeshta๐Ÿ“– ๐Ÿ’ป ๐Ÿ› Robert Rosca๐Ÿ“–
DICE_Lab๐Ÿ’ป Luis San Pablo๐Ÿ’ป โš ๏ธ ๐Ÿ“– Pastukhov Nikita๐Ÿ“– James O'Claire๐Ÿ“– Pete๐Ÿ“– Alexandre Richonnier๐Ÿ’ป ๐Ÿ“– betaboon๐Ÿ’ป
Dennis Brakhane๐Ÿ’ป ๐Ÿ› Pragy Agarwal๐Ÿ“– Piotr Dybowski๐Ÿ“– Konrad Szczurek๐Ÿ“– โš ๏ธ Orell Garten๐Ÿ’ป ๐Ÿ“– โš ๏ธ Julien๐Ÿ“– Leejay Hsu๐Ÿšง ๐Ÿš‡ ๐Ÿ“–
Michiel W. Beijen๐Ÿ“– L. Bao๐Ÿ“– Jarred Glaser๐Ÿ“– Hunter Boyd๐Ÿ“– Cesar Giulietti๐Ÿ“– Marcus Lim๐Ÿ“– Henry Zhou๐Ÿ› ๐Ÿ’ป
William Stam๐Ÿ“– andrew do๐Ÿ’ป โš ๏ธ ๐Ÿ“– Boseong Choi๐Ÿ’ป โš ๏ธ Kim Minki๐Ÿ’ป ๐Ÿ“– Jeongseop Lim๐Ÿ“– FergusMok๐Ÿ“– ๐Ÿ’ป โš ๏ธ Manu Singhal๐Ÿ“–
Jerry Wu๐Ÿ“– horo๐Ÿ› Ross Titmarsh๐Ÿ’ป Mike Korneev๐Ÿ“– Patrick Neise๐Ÿ’ป Jean Arhancet๐Ÿ› Leo Alekseyev๐Ÿ’ป
aranvir๐Ÿ“– ๐Ÿ’ป โš ๏ธ bunny-therapist๐Ÿ’ป Ben Luo๐Ÿ“– Hugo van Kemenade๐Ÿ“– Michael Gerbig๐Ÿ“– CrisOG๐Ÿ› ๐Ÿ’ป โš ๏ธ harryle๐Ÿ’ป โš ๏ธ
James Bennett๐Ÿ› sherbang๐Ÿ“– Carl Smedstadโš ๏ธ Taein Min๐Ÿ“– Stanislav Lyu.๐Ÿ› Tibor Reissโš ๏ธ ๐Ÿ“– ๐Ÿ’ป Alex๐Ÿ› ๐Ÿ’ป
Joren Six๐Ÿ“– jderrien๐Ÿ“– PossiblePanda๐Ÿ“– evstrat๐Ÿš‡ Ikko Eltociear Ashimine๐Ÿ“– Taimur Ibrahim๐Ÿ“– l-armstrong๐Ÿ“–
Anuranjan Srivastava๐Ÿ’ป Simon Joseph๐Ÿ“– Abel Kidanemariam๐Ÿ’ป โš ๏ธ ๐Ÿ“– Trim21๐Ÿ’ป โš ๏ธ Agustin Arce๐Ÿ“– Farhan Ali Raza๐Ÿ“– Fabian๐Ÿ’ป
Mohammed Babelly๐Ÿ’ป Charles Duffy๐Ÿ’ป Evgeny Demchenko๐Ÿ“– โš ๏ธ Olzhas Arystanov๐Ÿ› ๐Ÿ“– Vikash๐Ÿ’ป Jordan Russell๐Ÿ“– โš ๏ธ ๐Ÿ’ป Steven Loria๐Ÿ“–
oek1ng๐Ÿ’ป Vladislav๐Ÿ“– Edgars๐Ÿ“– Jianqi Pan๐Ÿ’ป PokkaKiyoโš ๏ธ Sergei Aleshin๐Ÿ’ป Igor Drokin๐Ÿ’ป โš ๏ธ ๐Ÿ“–
Tanay Kedia๐Ÿ’ป โš ๏ธ ๐Ÿ“–

This project follows the all-contributors specification.
Contributions of any kind welcome!


File: docs/admonitions/sync-to-thread-info.rst

.. admonition:: Synchronous and asynchronous callables
:class: important

text
Both synchronous and asynchronous callables are supported. One important aspect of
this is that using a synchronous function which perform blocking operations, such
as I/O or computationally intensive tasks, can potentially block the main thread
running the event loop, and in turn block the whole application.

To mitigate this, the ``sync_to_thread`` parameter can be set to ``True``, which
will result in the function being run in a thread pool.

If a synchronous function is non-blocking, setting ``sync_to_thread`` to ``False``
will tell Litestar that the user is sure about its behavior
and the function can be treated as non-blocking.

If a synchronous function is passed, without setting an explicit ``sync_to_thread``
value, a warning will be raised.

.. seealso::

    :doc:`/topics/sync-vs-async`

File: docs/migration/fastapi.rst

:orphan:

For FastAPI and Starlette users

This content has moved to :doc:/onboarding/fastapi


File: docs/migration/flask.rst

:orphan:

From Flask

This content has moved to :doc:/onboarding/flask


File: docs/migration/index.rst

:orphan:

Onboarding from other frameworks

This content has moved to :doc:/onboarding/index


File: docs/reference/channels/backends/asyncpg.rst

asyncpg

.. automodule:: litestar.channels.backends.asyncpg
:members:


File: docs/reference/channels/backends/index.rst

backends

.. toctree::

text
base
memory
redis
psycopg
asyncpg

File: docs/reference/channels/backends/psycopg.rst

psycopg

.. automodule:: litestar.channels.backends.psycopg
:members: