The causes could be:

  1. The name of the file - fastapi.py, if you name it in this could way you would get import errors. (Avoid filenames similar to package names)
  2. Installing on other environments. Most of the time it happens when you use both Conda and PiP on you system.
  3. If you run the code from VS Code, check if the same interpreter is selected.

Verify the installation:

$ pip list | grep fastapi

Suggestions:

OPT Virtual Environments to avoid these troubles.

Thank you!

Answer from Mahimai Raja J on Stack Overflow
Discussions

Can't find FastAPI module?
This could happen when you have fastapi installed globally (outside of the venv) and uvicorn is in the venv or vice versa , make sure you only have the packages in the venv only More on reddit.com
🌐 r/FastAPI
6
1
October 29, 2021
Import FastAPI does not work.
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 ... More on github.com
🌐 github.com
4
March 14, 2021
connecting localhost fastapi to react app [closed]
I am trying to develop a react app that connects to a python fastapi server. I am developing the frontend and the backend both on my local computer. When I try to use the fetch API to get data from... More on stackoverflow.com
🌐 stackoverflow.com
Import Error in Main.py
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 ... More on github.com
🌐 github.com
5
December 15, 2021
🌐
Medium
medium.com β€Ί @littechie β€Ί troubleshooting-import-module-error-in-python-a-solution-that-worked-901e2e2efb1b
Troubleshooting β€œImport Module” Error in Python: A Solution That Worked | by Lit Techie | Medium
July 26, 2023 - After spending considerable time debugging and trying various solutions, I finally managed to resolve the issue. In this blog post, I'll share my journey of tackling this problem and the solution that eventually worked for me. ... When attempting to import the β€œredis” module in my FastAPI project, I encountered the error message, β€œImport β€˜redis’ could not be resolved from source PylancereportMissingModuleSource.” Despite installing the required module, the issue persisted, leading me to believe that it might be related to the virtual environment setup.
🌐
Reddit
reddit.com β€Ί r/fastapi β€Ί can't find fastapi module?
r/FastAPI on Reddit: Can't find FastAPI module?
October 29, 2021 -

Please help, I must be doing something dumb.

I've been using FastAPI at work for a few weeks, and enjoying it. I wanted to try it on a personal project, so I started a new repo and tried to run Hello World.

This is the whole text of main.py:

import uvicorn
from fastapi import FastAPI

app = FastAPI()

@ app.get("/")
async def root():
return {"message": "Hello World"}

if __name__ == "__main__":
uvicorn.run("main:app", host="127.0.0.1", port=5000, log_level="info")

(The space after the @ sign is to stop reddit treating that as a username, it doesn't exist in the source file.)

I can run this from the command line with the Python command, and it works fine:

python3 main.py

But if I try to run it with uvicorn, I get a long message that ends with:

from fastapi import FastAPI

ModuleNotFoundError: No module named 'fastapi'

I created a virtual environment when I started the project, and if I deactivate it, I get the same error using the Python command line that I get using the uvicorn command line. When I restart the virtual environment, the Python command line works fine.

So I guess I need to let uvicorn see the modules that exist in the virtual environment, right? How can I do that?

🌐
DEV Community
dev.to β€Ί drsimplegraffiti β€Ί fast-api-part-1--j2l
Fast Api [part 1 ] - DEV Community
March 31, 2022 - from typing import Optional from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} class Person(BaseModel): name: str age: int | None = None tall: bool = False @app.post("/persons") async def create_person(person: Person): return {"data": f"my name is {person.name.upper()} and i am {person.age} years old"}
🌐
Sentry
sentry.io β€Ί sentry answers β€Ί vs code β€Ί fix pylance resolvemissingimports in vs code
Fix Pylance resolveMissingImports in VS Code | Sentry
July 15, 2024 - If you previously installed fastapi to the virtual environment, the resolveMissingImports error should now disappear.
🌐
Sling Academy
slingacademy.com β€Ί article β€Ί resolving-fastapi-error-could-not-import-module-api
Resolving FastAPI Error: β€˜Could not import module β€˜api” - Sling Academy
This results in an error because neither module can be fully imported without the other. Identifying and restructuring the code to remove circular dependencies can resolve the error. Review your api module and any other modules it imports to identify circular references.
Find elsewhere
🌐
GitHub
github.com β€Ί fastapi β€Ί fastapi β€Ί issues β€Ί 2951
Import FastAPI does not work. Β· Issue #2951 Β· fastapi/fastapi
March 14, 2021 - I already checked if it is not related to FastAPI but to Swagger UI.
Author Β  estkae
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 72808630 β€Ί connecting-localhost-fastapi-to-react-app
connecting localhost fastapi to react app [closed]
How do I resolve this? My backend is on port 80 and my frontend is on port 3000. If there is any more information I could provide to make this post more clear please let me know. I am relatively new to dealing with APIS and JS ... import math from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware myApp = FastAPI() userInput = 0 origins = [ "http://localhost:3000", "localhost:3000" ] app.add_middleware( CORSMiddleware, allow_origins = origins, allow_credentials = True, allow_methods = ["*"], allow_headers = ["*"] ) @myApp.get("/") def default(): return "enter a number after a slash in the URL" @myApp.get("/is-prime") def is_prime(): prime = True sqrt = int(math.sqrt(userInput)) for i in range(2, sqrt + 1): if userInput % i == 0: prime = False break return {"prime": prime}
🌐
GitHub
github.com β€Ί fastapi β€Ί fastapi β€Ί issues β€Ί 4281
Import Error in Main.py Β· Issue #4281 Β· fastapi/fastapi
December 15, 2021 - 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 ...
Author Β  tonyhart7
🌐
Sentry
sentry.io β€Ί sentry answers β€Ί fastapi β€Ί modulenotfounderror when working with fastapi in python
ModuleNotFoundError when working with FastAPI in Python | Sentry
February 15, 2024 - The best way to solve these issues and ensure that our project runs consistently on different systems is to create a virtual environment and use that environment every time we run the code in our project.
🌐
PyPI
pypi.org β€Ί project β€Ί fastapi
fastapi Β· PyPI
And it's intended to be the FastAPI of CLIs. ⌨️ πŸš€ ... Starlette for the web parts. Pydantic for the data parts. Create and activate a virtual environment and then install FastAPI: ... Note: Make sure you put "fastapi[standard]" in quotes to ensure it works in all terminals. ... from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: str | None = None): return {"item_id": item_id, "q": q}
      Β» pip install fastapi
    
Published Β  Apr 23, 2026
Version Β  0.136.1
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί having problems, specifically with imports not resolved.
r/learnpython on Reddit: Having problems, specifically with imports not resolved.
December 27, 2024 -

They are called Pip’s I believe. Not totally sure if I need to download them to my computer or if I can copy and paste the Bash into the line of code. I created the program with the help of YouTube but unfortunately I can’t find a video that helps with this problem. Been working at it for a few days now with no resolution lol so anything helps, thanks

Top answer
1 of 16
345

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.
2 of 16
25

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
🌐
Visual Studio Code
code.visualstudio.com β€Ί docs β€Ί python β€Ί tutorial-fastapi
FastAPI Tutorial in Visual Studio Code
November 3, 2021 - from fastapi import FastAPI, HTTPException from models import ItemPayload Β· Now add the following line right below app = FastAPI():
🌐
Bobby Hadz
bobbyhadz.com β€Ί blog β€Ί python-no-module-named-fastapi
ModuleNotFoundError: No module named 'fastapi' in Python | bobbyhadz
April 10, 2024 - To solve the error, install the module by running the pip install fastapi command. Open your terminal in your project's root directory and install the fastapi module. ... Copied!# πŸ‘‡οΈ In a virtual environment or using Python 2 pip install ...