Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI throws an error (Error loading ASGI app. Could not import module "api")

I tried to run FastAPI using uvicorn webserver but it throws an error.

I run this command,

uvicorn api:app --reload --host 0.0.0.0

but there is an error in the terminal.

Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
Started reloader process [23445]
Error loading ASGI app. Could not import module "api".
Stopping reloader process [23445]
like image 914
Pokisutra Avatar asked Mar 23 '20 18:03

Pokisutra


2 Answers

TL;DR

Add the directory name in front of your filename

uvicorn src.main:app 

or cd into that directory

cd src
uvicorn main:app 

Long Answer

It happens because you are not in the same folder with your FastAPI app instance more specifically:

Let's say i have an app-tree like this;

my_fastapi_app/
├── app.yaml
├── docker-compose.yml
├── src
│   └── main.py
└── tests
    ├── test_xx.py
    └── test_yy.py

$ pwd         # Present Working Directory
/home/yagiz/Desktop/my_fastapi_app

I'm not inside the same folder with my app instance, so if I try to run my app with uvicorn I'll get an error like yours

$ uvicorn main:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [40645] using statreload
ERROR:    Error loading ASGI app. Could not import module "main".

The answer is so simple, add the folder name in front of your filename

uvicorn src.main:app --reload

or you can change your working directory

cd src 

Now i'm inside of the folder with my app instance

src
└── main.py

Run your uvicorn again

$ uvicorn main:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [40726] using statreload
INFO:     Started server process [40728]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
like image 107
Yagiz Degirmenci Avatar answered Nov 15 '22 22:11

Yagiz Degirmenci


One reason this might be happening is that you are using:

uvicorn src/main:app --reload    

instead of the correct syntax:

uvicorn src.main:app --reload 

Notice the . instead of the /
Currently auto-completion in the terminal suggests the wrong format.


That's assuming that:

(1) your structure is something like this:

project_folder/
├── some_folder
├── src
│   └── main.py
└── tests
    ├── test_xx.py
    └── test_yy.py

(2) your FastAPI() object is indeed assigned to an object named app in main.py:

app = FastAPI()

(3) you are running the uvicorn command from the project_folder, e.g.:

(venv) <username>@<pcname>:~/PycharmProjects/project_folder$ uvicorn src.main:app --reload
like image 10
user Avatar answered Nov 15 '22 21:11

user