Events: startup - shutdown

Warning

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 Sub Applications - Mounts.

startup event

To add a function that should be run before the application starts, declare it with the event "startup":

  1. from fastapi import FastAPI
  2. app = FastAPI()
  3. items = {}
  4. @app.on_event("startup")
  5. async def startup_event():
  6. items["foo"] = {"name": "Fighters"}
  7. items["bar"] = {"name": "Tenders"}
  8. @app.get("/items/{item_id}")
  9. async def read_items(item_id: str):
  10. return items[item_id]

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 = FastAPI()
  3. @app.on_event("shutdown")
  4. def shutdown_event():
  5. with open("log.txt", mode="a") as log:
  6. log.write("Application shutdown")
  7. @app.get("/items/")
  8. async def read_items():
  9. return [{"name": "Foo"}]

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

Info

In the open() function, the mode="a" means “append”, so, the line will be added after whatever is on that file, without overwriting the previous contents.

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

You can read more about these event handlers in Starlette’s Events’ docs.