Database Connections Using Lifespan Events in FastAPI

In FastAPI, lifespan events provide a mechanism to execute code before or after the application starts or stops. This is particularly useful for managing database connections, ensuring that they are established before the application starts serving requests and closed after the application shuts down.

Creating Lifespan Events

Import Necessary Modules:

Python

from fastapi import FastAPI, Lifespan
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import sessionmaker

Define a Lifespan Function:

Python

async def startup() -> None:
engine = create_async_engine(DATABASE_URL)
async_session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
app.state.db = async_session

async def shutdown() -> None:
await app.state.db.close()

The startup function creates the database engine and session factory and stores them in the application’s state. The shutdown function closes the database session when the application is shutting down.

Create a FastAPI Instance:

Python

app = FastAPI(lifespan=Lifespan(startup=startup, shutdown=shutdown))

Using the Database Connection

You can now access the database session from your endpoints:

Python

from fastapi import APIRouter, Depends

router = APIRouter()

@router.post("/users")
async def create_user(user: User, db: Session = Depends(lambda: app.state.db)):
    async with db:
        db.add(user)
        await db.commit()
        await db.refresh(user)
        return user

Benefits of Using Lifespan Events

  • Database connections are managed in a single place, making your code more organized and easier to maintain.
  • Lifespan events ensure that database connections are closed properly when the application shuts down, preventing resource leaks.
  • Using the Depends decorator, you can inject the database session into your endpoints, making your code more modular and testable.
Running FastAPI Tests in ‘Test’ Mode
Setting Up Async Databases with FastAPI

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?