0Pricing
Python Academy · Lesson

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 rows

All lessons in this course

  1. FastAPI Project Setup and First Endpoint
  2. Path Parameters, Query Params, and Request Bodies
  3. Dependency Injection and Authentication
  4. Async Endpoints and Database Integration
← Back to Python Academy