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.
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.
# settings.py
DATABASE_TYPE = "sqlite"
DATABASE_URL = "sqlite:///lenapi.db"
ACTIVATE_ASYNC = TrueUse AsyncSession in a route
Annotate a handler parameter with SQLAlchemy AsyncSession. LenAPI opens and closes the request-scoped session for you.
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()Use async model helpers
The asynchronous ORM helpers are prefixed with a: acreate, aget, afilter, asave, adelete, aaggregate, and acount. Await each database operation.
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)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 -m pip install 'lenapi[mysql,async-mysql]'
# PostgreSQL
python -m pip install 'lenapi[postgres,async-postgres]'An async route does not make blocking third-party I/O asynchronous. Use an async client or explicitly offload blocking work.