Bird
0
0

Consider this FastAPI code snippet:

medium📝 component behavior Q13 of 15
FastAPI - Middleware and Hooks
Consider this FastAPI code snippet:
from fastapi import FastAPI
app = FastAPI()

@app.on_event("startup")
async def startup_event():
    print("Starting app")

@app.on_event("shutdown")
async def shutdown_event():
    print("Stopping app")

@app.get("/")
async def read_root():
    return {"message": "Hello"}

What will be printed when the server starts and then stops?
AStopping app (on start), Starting app (on shutdown)
BStarting app (on start), Stopping app (on shutdown)
COnly Starting app when server starts
DNo output printed at all
Step-by-Step Solution
Solution:
  1. Step 1: Identify startup and shutdown prints

    The startup_event prints "Starting app" when the app starts, and shutdown_event prints "Stopping app" when the app stops.
  2. Step 2: Understand event timing

    These events run once each: startup at launch, shutdown at server stop.
  3. Final Answer:

    Starting app (on start), Stopping app (on shutdown) -> Option B
  4. Quick Check:

    Startup prints "Starting app", shutdown prints "Stopping app" [OK]
Quick Trick: Startup prints on launch, shutdown prints on stop [OK]
Common Mistakes:
MISTAKES
  • Swapping startup and shutdown outputs
  • Expecting prints on every request
  • Thinking no output occurs without explicit call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes