Async Endpoints and Database Integration
Write async route handlers and connect to a database with SQLAlchemy.
async def Endpoints
Declare route handlers with async def for non-blocking I/O. Use def for CPU-bound or blocking operations (FastAPI runs them in a thread pool).
from fastapi import FastAPI
import asyncio
app = FastAPI()
@app.get("/slow")
async def slow():
await asyncio.sleep(1) # non-blocking
return {"done": True}asyncpg for PostgreSQL
asyncpg is a fast, async PostgreSQL driver. Use a connection pool shared across requests.
# pip install asyncpg
import asyncpg, asyncio
async def main():
pool = await asyncpg.create_pool("postgresql://user:pass@host/db")
async with pool.acquire() as conn:
rows = await conn.fetch("SELECT id, name FROM users")
await pool.close()
return rowsAll lessons in this course
- FastAPI Project Setup and First Endpoint
- Path Parameters, Query Params, and Request Bodies
- Dependency Injection and Authentication
- Async Endpoints and Database Integration