DocumentationAsync endpoints and database access
API referenceGitHub

Async endpoints and database access

Use async handlers and SQLAlchemy AsyncSession with the same configured database URL.

Work through each step in order. The examples use the generated LenAPI project structure and are designed to be adapted to your app.

01

Enable async access in settings

ACTIVATE_ASYNC enables async database resources alongside the selected DATABASE_URL. Async SQLite is available by default; production drivers can be installed from their optional extras.

Python
# settings.py
DATABASE_TYPE = "sqlite"
DATABASE_URL = "sqlite:///lenapi.db"
ACTIVATE_ASYNC = True
02

Use AsyncSession in a route

Annotate a handler parameter with SQLAlchemy AsyncSession. LenAPI opens and closes the request-scoped session for you.

Python
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

@app.get("/students")
async def list_students(db: AsyncSession):
    result = await db.scalars(select(Student))
    return result.all()
03

Use async model helpers

The asynchronous ORM helpers are prefixed with a: acreate, aget, afilter, asave, adelete, aaggregate, and acount. Await each database operation.

Python
student = await Student.acreate(person_name="Ada", course="Python")
student = await Student.aget(id=student.id)
student.course = "Databases"
await student.asave()

page = await Student.afilter(course="Databases").all(limit=20)
04

Install the matching async driver

Keep sync and async access on the same configured database backend; choose the required driver extra for MySQL or PostgreSQL.

Python
python -m pip install 'lenapi[mysql,async-mysql]'
# PostgreSQL
python -m pip install 'lenapi[postgres,async-postgres]'
TIP

An async route does not make blocking third-party I/O asynchronous. Use an async client or explicitly offload blocking work.