fastapi: Error loading ASGI app. Could not import module "src.main"

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

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 24 (5 by maintainers)

Most upvoted comments

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.

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.

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.

Looks like you’re running uvicorn src.main:app --reload instead of uvicorn main:app --reload

just add a empty file in the same folder with this name init.py

@peterbb148 what is the name of the file where that code is located?

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.

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

import database

or

from . import database

I did:

from src import database

or

import src.database

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.