I have a project spread out across three repos, two of which contain an API: a main API and a helper API, which is called by the main API. Both APIs are implemented in FastAPI (fastapi==0.89.0
); I'm using Python 3.9.12 in VSCode. The structure of both repositories is similar to each other:
# repo structure for both API repos:
|__ app
|__ main.py
|__ routers.py
|__ #some subfolders
Each repo has its own virtual environment. The source code in the non-API repo is installed in the virtual environments of both API repos, in editable mode (pip install -e
). The main API is running on port 8000; the helper API on port 8005:
# repo 1, main.py
import uvicorn
from fastapi import FastAPI
from gunicorn.http import message
from app.routers import router
app = FastAPI(description="main API")
app.include_router(router)
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)
Script for helper API:
# repo 2, main.py
from fastapi import FastAPI
import uvicorn
from gunicorn.http import message
from app.routers import router
# fastapi app
app = FastAPI(
title="helper API")
app.include_router(router)
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8005)
The routers.py
scripts in the two repos is identical, except for the tags passed to include_router
:
from fastapi import APIRouter
from app.pipeline import view
router = APIRouter()
router.include_router(view.router, tags=["different tag here"])
When I run the two main.py scripts in separate terminals, the info that gets printed to these terminals is as expected:
# terminal for helper API
INFO: Started server process [4650]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8005 (Press CTRL C to quit)
# terminal for main API
INFO: Started server process [4681]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL C to quit)
However, when I visit http://127.0.0.1:8000/docs
, then the endpoints of the helper API, and not the main API, are exposed there. So the helper API somehow seems to 'override' the main API on port 8000, and its endpoints are accessible at 2 ports: 8000 and 8005. The endpoints of the main API, by contrast, are not accessible anywhere. At first I thought it might be due to my VSCode settings, but some googling proved fruitless. Any idea how to fix this?
CodePudding user response:
I found the root cause: at some point I must have prepended the helper API repo to my PYTHONPATH, the result being that when I ran the two main.py scripts, one and the same router got imported. Removing the helper API repo from the PYTHONPATH variable fixed the problem.