Bird
0
0

Why does this FastAPI startup event handler fail?

medium📝 Debug Q7 of 15
FastAPI - Middleware and Hooks
Why does this FastAPI startup event handler fail?
from fastapi import FastAPI
app = FastAPI()

@app.on_event("startup")
def startup():
    import asyncio
    asyncio.run(init_db())
AMissing await keyword before init_db()
BCalling asyncio.run inside event handler causes event loop error
Cinit_db() must be synchronous
DEvent handler must be named on_startup
Step-by-Step Solution
Solution:
  1. Step 1: Understand asyncio.run usage

    Calling asyncio.run() inside an already running event loop (FastAPI's) causes an error.
  2. Step 2: Correct approach

    Define the startup handler as async and await init_db() directly.
  3. Final Answer:

    Calling asyncio.run inside event handler causes event loop error -> Option B
  4. Quick Check:

    Don't call asyncio.run inside async event handlers [OK]
Quick Trick: Use async def and await, not asyncio.run inside handlers [OK]
Common Mistakes:
MISTAKES
  • Using asyncio.run inside async context
  • Not making handler async
  • Misnaming event handler functions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes