Events: startup - shutdown

    The current page still doesn’t have a translation for this language.

    But you can help translating it: Contributing.

    You can define event handlers (functions) that need to be executed before the application starts up, or when the application is shutting down.

    These functions can be declared with async def or normal def.

    Warning

    Only event handlers for the main application will be executed, not for .

    In this case, the startup event handler function will initialize the items “database” (just a dict) with some values.

    You can add more than one event handler function.

    And your application won’t start receiving requests until all the startup event handlers have completed.

    shutdown event

    To add a function that should be run when the application is shutting down, declare it with the event "shutdown":

    1. from fastapi import FastAPI
    2. @app.on_event("shutdown")
    3. def shutdown_event():
    4. log.write("Application shutdown")
    5. @app.get("/items/")

    Here, the shutdown event handler function will write a text line "Application shutdown" to a file log.txt.

    Info

    Tip

    Notice that in this case we are using a standard Python open() function that interacts with a file.

    So, it involves I/O (input/output), that requires “waiting” for things to be written to disk.

    But open() doesn’t use async and await.

    So, we declare the event handler function with standard def instead of async def.

    Info