0
0
FastAPIframework~30 mins

Lifespan context manager in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Lifespan Context Manager in FastAPI
📖 Scenario: You are building a simple FastAPI web application that needs to perform setup and cleanup tasks when the app starts and stops. This is common when connecting to databases or opening files.
🎯 Goal: Learn how to use the lifespan context manager in FastAPI to run code during app startup and shutdown.
📋 What You'll Learn
Create a FastAPI app instance
Define a lifespan context manager function
Use asynccontextmanager from contextlib
Print messages on startup and shutdown inside the lifespan
Use the lifespan context manager when creating the FastAPI app
💡 Why This Matters
🌍 Real World
Many web applications need to initialize resources like database connections or caches when they start, and clean them up when they stop. The lifespan context manager in FastAPI helps manage these tasks cleanly.
💼 Career
Understanding how to manage app startup and shutdown is important for backend developers working with FastAPI or similar frameworks to ensure reliable and maintainable services.
Progress0 / 4 steps
1
Create the FastAPI app instance
Import FastAPI from fastapi and create a variable called app that is an instance of FastAPI().
FastAPI
Need a hint?

Use from fastapi import FastAPI and then app = FastAPI().

2
Define the lifespan context manager function
Import asynccontextmanager from contextlib. Define an async function called lifespan that uses the @asynccontextmanager decorator. Inside it, print "Starting up...", then yield, then print "Shutting down...".
FastAPI
Need a hint?

Use @asynccontextmanager to decorate an async function named lifespan. Print before and after yield.

3
Use the lifespan context manager in the FastAPI app
Modify the app variable to pass the lifespan function as the lifespan parameter when creating the FastAPI instance.
FastAPI
Need a hint?

Pass lifespan=lifespan when creating the FastAPI app.

4
Add a simple route to test the app
Add a route to app using the @app.get("/") decorator. Define an async function called read_root that returns a dictionary with {"message": "Hello World"}.
FastAPI
Need a hint?

Use @app.get("/") and define async def read_root() returning the dictionary.