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.
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
Bilalharoon opened this issue a year ago · comments
First Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google «How to X in FastAPI» and didn’t find any information.
- I already read and followed all the tutorial in the docs and didn’t find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
Example Code
from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from fastapi.security.oauth2 import OAuth2PasswordRequestForm from . import models from . import services from .database import engine, get_db from passlib.context import CryptContext from sqlalchemy.orm import Session from datetime import datetime, timedelta app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl='login') pwd_context = CryptContext(schemes=['bcrypt'], depracated='auto') models.Base.metadata.create_all(bind=engine) SECRET_KEY = '[SECRET KEY]' ALGORITHM = 'HS256' ACCESS_TOKEN_EXPIRE_MINUTES = 30 @app.get("/") async def root(): return {"message": "Hello World"} @app.get("/test/") async def test(token:str = Depends(oauth2_scheme)): return {'token', token} @app.post('/login/{method}') async def login(method: str, form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db), ): user = services.authenticate_user(form_data.username, form_data.password) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"}, ) access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) access_token = services.create_access_token( data={"username": user.username, "email": user.email}, expires_delta=access_token_expires ) return {"access_token": access_token, "token_type": "bearer"}
Description
I saw the solution is changing ‘main’ -> ‘src.main’ so I tried that, but the same problem is occuring Even if I use ‘cd src’ to move to src and run ‘uvicorn main:app —reload’, errors continue. What do I need?
Operating System
Linux
Operating System Details
WSL 2
FastAPI Version
0.68.1
Python Version
3.8.10
Additional Context
No response
Can you give us your directory structure and the directory you are in when you run your uvicorn command?
You should be in the same directory as your main file to run uvicorn main:app
so it will go to the main.py file and find the app object
Can you give us your directory structure and the directory you are in when you run your uvicorn command?
You should be in the same directory as your main file to run
uvicorn main:app
so it will go to the main.py file and find the app object
Where are you running your command from? what is the directory? Could you run pwd
and an ls
pwd:
/home/bilalharoon/Projects/Kalaam/kalaam-fastapi/src
ls from inside src
__init__.py __pycache__ database.py main.py models.py schemas.py services.py
ls from outside src
alembic kalaam.db requirements.txt src venv
and uvicorn main:app --reload
isnt working? Can you share the console output?
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [314] using watchgod
ERROR: Error loading ASGI app. Could not import module "src.main".
Looks like you’re running uvicorn src.main:app --reload
instead of uvicorn main:app --reload
I tried both. both of them don’t work
Can you confirm by running the whole sequence? It should be picking it up if the entrypoint you are running from is correct
pwd
ls -l
uvicorn main:app --reload
Please add the output so we can help — this isn’t a fastapi issue, it is the way you’re running your code.
So I made it work and I have no idea how. But what I did was change all the imports to module imports.
so instead of
or
I did:
or
Have exact same problem. Here’s my code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Command line:
uvicorn fastapi:app --reload --port 8001
INFO: Will watch for changes in these directories: ['/Users/peter/Git/peterbb148/Python']
INFO: Uvicorn running on http://127.0.0.1:8001 (Press CTRL+C to quit)
INFO: Started reloader process [3942] using statreload
ERROR: Error loading ASGI app. Could not import module "fastapi".
All file are in the same directory.
@peterbb148 what is the name of the file where that code is located?
This should be re-opened. The issue can arise for something different that is covered in this ticket in terms of solutions.
The error message is misleading in the sense that it can appear for other reasons than «not being able to find module».
In my case the culprit is import in one of the submodules with from app import dictionary_lookup
which is exactly the way in which all the other sub-modules handle the imports. For some reason, doing this in a particular file causes the fastapi error.
EDIT: It turns out to be simple case of having imports in wrong order.
Given how many people are dealing with this issues, and many threads end up with no resolution, probably a good time to give ability to have verbosity, or clear the language of the error.
importing FastAPI before import uvicorn fixed it for me
just add a empty file in the same folder with this name init.py
I just encountered the exact same problem. I noticed the error resolves as soon as I comment out certain imports. «
from fastapi import FastAPI, Response, status, HTTPException, Depends, APIRouter
from fastapi.params import Body
import psycopg2
from psycopg2.extras import RealDictCursor
import time
from . import models, utils, Schemas
from .database import engine, get_db, SessionLocal
from sqlalchemy.orm import Session
from .routers import post2, user2
The server starts again after I remove the last import.
This is the command I am using:
uvicorn Apps.main:app --reload
These are the from post2 (same for user2) directories from routers.
from fastapi import FastAPI, Response, status, HTTPException, Depends, APIRouter
from sqlalchemy.orm import Session
from ..database import get_db
from .. import models, utils, Schemas
But I do require to use the APIRouter which is the main reason for separating all the path operations from main file.
change the name of your file and try again
The error message will appear if there is circular import error. Unfortunately, instead of circular import error the “Error loading ASGI app. Could not import module ….” is reported.
the same error occurs in Pycharm cmd with the correct src folder
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [12072] using statreload
WARNING: The —reload flag should not be used in production on Windows.
ERROR: Error loading ASGI app. Could not import module «app».
I had the same issue and it happened without any change from myside.
I simply solved it by just creating another python script(copied my file from the app folder) in the same virtual environment folder.
The error message will appear if there is circular import error. Unfortunately, instead of circular import error the “Error loading ASGI app. Could not import module ….” is reported.
I got the mentioned error message but was able to solve this problem after solving a circular import error I had.
I had the same issue with a very minimal example:
from fastapi import FastAPI app = FastAPI() @app.get('/') async def root(): return {"message": "Basic API"}
Since everyone seems to be pointing to import issues, I added an unused import before as I had in previous FastAPI work I’ve done and it works… Can’t really understand what is happening here but with the below it works:
import pandas as pd #Only modification from fastapi import FastAPI app = FastAPI() @app.get('/') async def root(): return {"message": "Basic API"}
I got absolutely the same issue, Error loading ASGI app. Attribute «app» not found in module «main».
While it was like this, it didn’t work:
from fastapi import FastAPi
app = FastAPI()
but since I’ve changed the import, it started:
import fastapi
app = fastapi.FastAPI()
just in case, someone else will get the same issue. Windows 11, home edition.
Hi guys. I was trying to run FastAPI using uvicorn webserver and I faced the following error: FastAPI throws an error (Error loading ASGI app. Could not import module “api”). I found some solutions to solve this error. So let’s see that.
Contents
- How To fix FastAPI throws an error (Error loading ASGI app. Could not import module «api») error?
- Answer 1 : add the directory name
- Answer 2 : add package name before main
- Final Word
- Also, Look at this solvderror
- How To fix FastAPI throws an error (Error loading ASGI app. Could not import module “api”) error?
To fix FastAPI throws an error (Error loading ASGI app. Could not import module “api”) error just add the directory name. You should just add the directory name in front of your filename
uvicorn src.main:app
- FastAPI throws an error (Error loading ASGI app. Could not import module “api”)
To fix FastAPI throws an error (Error loading ASGI app. Could not import module “api”) error just add package name before main. Just add package name before main to solve this error.
uvicorn src.main:app --reload
Answer 1 : add the directory name
You should just add the directory name in front of your filename
uvicorn src.main:app
Answer 2 : add package name before main
Just add package name before main to solve this error.
uvicorn src.main:app --reload
Final Word
I hope this will help you to solve this error. Thank you!
Also, Look at this solvderror
- Could not build wheels since package wheel is not installed
- error showing : unable to locate package python on Termux
- Python 3.7 Error: Unsupported Pickle Protocol 5
- “Import could not be resolved” reported by Pyright
- The minCompileSdk (31) specified in a dependency’s AAR metadata
This was quite annoying for me, so just in case someone finds this question but none of the answers above can help, here is what I did.
Add the following main method to the main file of my app:
if __name__ == "__main__":
port = os.getenv("PORT")
if not port:
port = 8080
uvicorn.run(app, host="0.0.0.0", port=8080)
Then run this using python instead of running the uvicorn
module:
python -m app.main
The output now was more useful:
Traceback (most recent call last):
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/runpy.py", line 193, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/runpy.py", line 86, in _run_code
exec(code, run_globals)
File "/Users/robert-andreidamian/Workspace/panprices/shelf-analytics-api/app/main.py", line 7, in <module>
from app.routers import auth, users, availability, data, overview
File "/Users/robert-andreidamian/Workspace/panprices/shelf-analytics-api/app/routers/overview.py", line 5, in <module>
from app.main import get_db
File "/Users/robert-andreidamian/Workspace/panprices/shelf-analytics-api/app/main.py", line 23, in <module>
app.include_router(overview.router)
AttributeError: partially initialized module 'app.routers.overview' has no attribute 'router' (most likely due to a circular import)
As you can see the problem was generated by a circular dependency issue. I ran into this when following the SQLAlchemy tutorial in the FastAPI documentation: https://fastapi.tiangolo.com/tutorial/sql-databases/ . As suggested, i created the get_db
function in my main file.
Before that I had already split the router in multiple files as explained in another section of the documentation: https://fastapi.tiangolo.com/tutorial/bigger-applications/.
This resulted in a circular dependency between the main file, that was importing the routing modules, and the routing modules that were importing the get_db
function from the main module.
Hope this saved some of your time and frustration!