How to Resolve Python "Error loading ASGI app. Could not import module '...'"
When launching a FastAPI application using an ASGI server like Uvicorn, a common startup error is Error loading ASGI app. Could not import module 'your_module_name' (e.g., main). This error indicates that Uvicorn, when trying to find and load your FastAPI application object, was unable to locate the specified Python file (.py) based on the path provided and the current working directory.
This guide explains the common causes of this import failure and provides clear, step-by-step solutions to get your FastAPI app running.
Understanding the Error: Uvicorn and Module Imports
ASGI servers like Uvicorn need to import your Python code to find the actual FastAPI application instance (the ASGI callable) that they will run. Python's import system relies heavily on the Current Working Directory (CWD) – the directory your terminal is currently focused on when you run the uvicorn command – and the specified module path. If Uvicorn cannot find the Python file based on these factors, it raises the "Could not import module" error.
The Uvicorn Command Structure (module:app)
The standard command format is uvicorn main:app --reload:
main: This refers to the Python filemain.py. Do not include the.pyextension here. If your file is inside a directory (package), you use dot notation (e.g.,src.main).:: Separator.app: This refers to the Python variable insidemain.pythat holds your FastAPI instance (usually created viaapp = FastAPI()).--reload: An optional flag for development that automatically restarts the server when code changes are detected.
Cause 1: Incorrect Current Working Directory
This is the most frequent cause. You are running the uvicorn command from a directory where the specified module path (e.g., main) doesn't make sense relative to that location.
Example Scenario:
Your project structure is:
my_fastapi_project/
├── venv/
└── src/
└── main.py <-- Contains 'app = FastAPI()'
If your terminal's CWD is my_fastapi_project/ and you run uvicorn main:app, Uvicorn looks for main.py directly inside my_fastapi_project/. It won't find it because it's inside the src/ subdirectory, leading to the error.