Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Node.js, PHP and APIs

FastAPI raises a RuntimeError when code inside it calls asyncio.run()

Your error

RuntimeError: asyncio.run() cannot be called from a running event loop1 more line it can show

Fix it fast

Most common cause, 1 of 3

An async def endpoint or dependency calls asyncio.run() on a coroutine

Await the coroutine directly.

Fix
@app.get("/items")
async def read_items():
    return await fetch_data()      # was: return asyncio.run(fetch_data())
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

RuntimeError: asyncio.run() cannot be called from a running event loop appears because Uvicorn already runs an event loop and every async def endpoint executes inside it. Replace asyncio.run(coro) with await coro. For a sync helper that calls asyncio.run, make the endpoint a plain def or use await asyncio.to_thread(helper). Applies to FastAPI 0.165 and Uvicorn 0.54.

  • Applies to FastAPI 0.165.0, Uvicorn 0.54.0, Python 3.14
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

List every asyncio.run call in the project and note where each one sits. Inside an async def means cause 1. Inside a plain def helper that an async endpoint calls means cause 2, and so does a traceback that runs through a library. At the top level of the module Uvicorn loads means cause 3.

Run this first
grep -rn "asyncio.run(" --include=*.py .

Then find the line you see in this list and open its fix:

  1. 1An async def endpoint or dependency calls asyncio.run() on a coroutineThe traceback goes straight from your async def function into asyncio.run, and the request returns 500 Internal Server Error
  2. 2A synchronous helper or library wrapper calls asyncio.run() and an async endpoint calls itThe traceback passes through a plain def function, often a library's sync client, between your endpoint and asyncio.run; the same helper works in a standalone script
  3. 3asyncio.run() runs at import time in the module Uvicorn loadsThe server crashes at start-up, Application startup complete is never logged, and the traceback runs through uvicorn/importer.py import_from_string

What does the error look like?

  • RuntimeError: asyncio.run() cannot be called from a running event loop
  • RuntimeWarning: coroutine 'fetch_data' was never awaited

Cause 1 of 3

An async def endpoint or dependency calls asyncio.run() on a coroutine

You seeThe traceback goes straight from your async def function into asyncio.run, and the request returns 500 Internal Server Error

Check

Python's documentation says asyncio.run() cannot be called while another asyncio event loop is running in the same thread. Uvicorn starts that loop before it serves anything, and an async def endpoint runs on it, so the call fails every time. The coroutine you passed is then dropped, which explains the never awaited warning.

Check
curl -i http://127.0.0.1:8000/items

Fix

Await the coroutine directly. The endpoint is already running on the event loop, so no new loop is needed.

Fix
@app.get("/items")
async def read_items():
    return await fetch_data()      # was: return asyncio.run(fetch_data())

Verify

Call the route again. It returns the data with status 200 and the RuntimeError is gone from the Uvicorn log.

Verify
curl -i http://127.0.0.1:8000/items

Confirmed by docs.python.org

Did this fix it?

Cause 2 of 3

A synchronous helper or library wrapper calls asyncio.run() and an async endpoint calls it

You seeThe traceback passes through a plain def function, often a library's sync client, between your endpoint and asyncio.run; the same helper works in a standalone script

Check

FastAPI runs a plain def path operation in an external threadpool, but a plain def utility that you call yourself runs directly in the caller. Called from an async def endpoint, that helper therefore sits on the loop's thread, and its internal asyncio.run fails there.

Check
grep -rn "asyncio.run(" .venv/lib/python3.14/site-packages/mylib/

Fix

Best: switch to the library's async API and await it. When only the sync helper exists, declare the endpoint with def so FastAPI moves it to a worker thread, or keep async def and hand the helper to asyncio.to_thread. Both run the helper on a thread with no loop of its own, where asyncio.run is allowed.

Fix
import asyncio

@app.get("/report")
def report():                       # option A: plain def, FastAPI uses its threadpool
    return mylib.get_report()

@app.get("/report2")
async def report2():                # option B: stay async, run the helper in a thread
    return await asyncio.to_thread(mylib.get_report)

Verify

Both routes return the report, and the log no longer shows the RuntimeError.

Verify
curl -i http://127.0.0.1:8000/report

Confirmed by fastapi.tiangolo.com

Did this fix it?

Cause 3 of 3

asyncio.run() runs at import time in the module Uvicorn loads

You seeThe server crashes at start-up, Application startup complete is never logged, and the traceback runs through uvicorn/importer.py import_from_string

Check

When you start uvicorn main:app, Uvicorn's Server.run opens the event loop first and only then imports the module named in main:app. Top-level setup code such as asyncio.run(init_db()) therefore executes inside a loop that is already running.

Check
grep -n "^asyncio.run(" main.py

Fix

Move one-time setup into a lifespan function and await it there. FastAPI runs the code before yield once, before the first request, and the code after yield at shutdown.

Fix
from contextlib import asynccontextmanager
from fastapi import FastAPI

@asynccontextmanager
async def lifespan(app: FastAPI):
    await init_db()          # was: asyncio.run(init_db()) at module level
    yield
    await close_db()

app = FastAPI(lifespan=lifespan)

Verify

Uvicorn logs Application startup complete and the routes that need the database answer.

Verify
uvicorn main:app --port 8000

Confirmed by fastapi.tiangolo.com

Did this fix it?

How do I stop it coming back?

  • Keep asyncio.run only in the entry point of standalone scripts and CLI tools, never in modules that a web app imports.
  • When a library offers both sync and async clients, use the async one in async def endpoints.
  • Add a test with FastAPI's TestClient that calls every route once, so a hidden asyncio.run fails in CI and not in production.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine on the same stack: stegnor.com, Menulo, ShopGo.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.