FastAPI cannot find my Python Package. It seems relatively obvious that this is an issue with Python paths and imports, however I do not know how to fix it.
What surprised me is that this worked when using Flask instead of FastAPI. I converted a small application from Flask to FastAPI, and this is when the import statements no longer were able to find my Python package.
I don’t know enough about the FastAPI-cli to understand what it does / does not do with paths to know how to fix it.
Here’s a very simple MWE.
# /fastapi/fastapi_mwe.py
from fastapi import FastAPI
from pydantic import BaseModel
from my_package import my_value
print(f'__name__={__name__}')
app = FastAPI()
class FastAPI_Value(BaseModel):
value: int
@app.get('/')
def root(fastapi_value: FastAPI_Value):
next_value = fastapi_value.value + my_value
return {
'next_value': next_value
}
# /my_package/__init__.py
my_value = 1
Here’s the project structure:
stack_overflow_mwe/
my_package/
__init__.py
fastapi/
fastapi_mwe.py
Here’s how I run fastapi_mwe.py
:
user@host:/home/user/stackoverflow_mwe/$ fastapi dev fastapi/fastapi_mwe.py
ModuleNotFoundError: No module named `my_package`
How should I structure this project and how can I fix this? I don’t really want to put the package my_package
into the subdirectory fastapi
, because this package should be totally independent of the fastapi wrapper/webserver. I should be able to create a new subfolder called flask_api
and be able to import my_package
from both locations.
I have also tried to avoid using .venv
and an editable install + pyproject.toml
. I am using virtual environments to manage dependencies (for example I did pip3 install fastapi
to install the fastapi package into a local .venv
). If there is no alternative, then I can create a pyproject.toml
and setup the local packages as an editable install, but I don’t really want to do this unless there is no alternative.