FastAPI - Lifespan

  • Learn how to run one-off startup and shutdown routines that manage shared resources across your application’s entire lifespan.

    Introduction

    You can run logic before the application starts up. This code executes once, before the app begins handling requests.

    Similarly, you can run logic when the application is shutting down. This code executes once, after the app has handled requests.

    Because this code runs right before the app starts and right after it stops, it spans the entire application lifespan.

    Typical use cases include preparing and cleaning up shared resources, such as a database connection pool or a loaded machine learning model.

    Lifespan

    You can define startup and shutdown logic with the app’s lifespan parameter using a Python - Context manager.

    @asynccontextmanager
    async def lifespan(app: FastAPI):
    # app.state is where the connection is created, which can be accessed later inside of views.
    # This is only run once during app startup.
    app.state.db = sqlite3.connect("test.db")
    try:
    # This is where the app runs all the URL route functions.
    yield
    finally:
    # This is run once when the app is shut down.
    app.state.db.close()
    # Just add the lifespan function to the app when it is instantiated.
    app: FastAPI = FastAPI(lifespan=lifespan)

    Here’s the idea:

    • Put initialization code before a yield.
    • Put cleanup code after the yield.
    • The code before yield runs once on startup; the code after yield runs once on shutdown.

    Test

    When you need lifespan to run in your tests, you can use the TestClient with a with statement:

    Testing Events

    Nota

    Starlette ASGIApp frameworks like FastAPI can leverage lifespan functions, which are generators.

    Underneath, in the ASGI technical specification, this is part of the Lifespan Protocol, and it defines events called startup and shutdown.