How to individual run file beside main.py in FASTAPI platform?
First Check
- [X] I added a very descriptive title to this issue.
- [X] I used the GitHub search to find a similar issue and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to Pydantic.
- [X] I already checked if it is not related to FastAPI but to Swagger UI.
- [X] I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- [X] I commit to help with one of those options 👆
Example Code
in db/database.py
from elasticsearch import Elasticsearch
from dataclasses import dataclass
from core.config import Settings
# from metering_api_gateway.core.config import Settings
Description
How can i individual test/run a python file beside main.py in FASTAPI framework?
Operating System
Linux
Operating System Details
I have similar question related to following
FastAPI Version
0.82
Python Version
3.8
Additional Context

How can i indiviudual test a file in FASTAPI framework?
i run by poetry run python3 db/database.py
it shows error "File "db/database.py", line 3, in
You should run from project root, right? i.e, your imports are relative to project root. And it is same for all python applications (or packages).
Edit: typo - project root
I think that it's a problem related to just imports.
If you are running ./db/database.py then your project's root is not in PYTHONPATH.
Since your imports are not relative, Python can't find them.
To fix this, you can for instance:
- run
db/database.pywith commandpython3 -m db.database(but I'm not sure how does it work with poetry) - this will ensure that your project's root is in path, - add project's root to environment variable
PYTHONPATH, - change imports to relative,
- or, I guess, many more...
Can you just do the whole code in database.py a function (e.g. runDatabase() and then in your root (i.e. main.py) do:
from database.py import *
runDatabase()
Thanks for the help here everyone! 👏 🙇
If that solves the original problem, then you can close this issue @apexbb ✔️
If not, please add a self-contained, minimal, reproducible, example that I can copy-paste to replicate it.
Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs.