0
0
FastAPIframework~15 mins

Startup and shutdown events in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Startup and Shutdown Events in FastAPI
📖 Scenario: You are building a simple FastAPI application that needs to perform actions when the app starts and stops. For example, you want to open a connection or print a message when the app starts, and clean up or print a message when the app stops.
🎯 Goal: Create a FastAPI app that prints messages on startup and shutdown events using the correct event decorators.
📋 What You'll Learn
Create a FastAPI app instance named app
Define a startup event handler function named startup_event that prints "App is starting"
Define a shutdown event handler function named shutdown_event that prints "App is shutting down"
Register the startup and shutdown event handlers using @app.on_event decorators
💡 Why This Matters
🌍 Real World
Web applications often need to prepare resources like database connections or caches when they start and clean them up when they stop. Startup and shutdown events help manage these tasks cleanly.
💼 Career
Understanding FastAPI lifecycle events is important for backend developers to write robust, maintainable web services that handle resource management properly.
Progress0 / 4 steps
1
Create the FastAPI app instance
Import FastAPI from fastapi and create an app instance called app.
FastAPI
Need a hint?

Use app = FastAPI() to create the app instance.

2
Define the startup event handler
Define a function called startup_event that prints "App is starting". Use the decorator @app.on_event("startup") to register it as the startup event handler.
FastAPI
Need a hint?

Use @app.on_event("startup") above the function definition.

3
Define the shutdown event handler
Define a function called shutdown_event that prints "App is shutting down". Use the decorator @app.on_event("shutdown") to register it as the shutdown event handler.
FastAPI
Need a hint?

Use @app.on_event("shutdown") above the function definition.

4
Complete the FastAPI app with startup and shutdown events
Ensure the full code includes the app instance and both event handlers startup_event and shutdown_event registered with @app.on_event decorators.
FastAPI
Need a hint?

Check that all parts are included and correctly decorated.