I'm having trouble with my FastAPI application when deployed in a Kubernetes pod. My application is exposed at https://api-gateway.example.com/myapp (myapp is part of the host), but OpenAPI was trying to fetch the JSON from https://api-gateway.example.com/api/v1/openapi.json (without myapp), resulting in a 404 error: Failed to load API definition.

Here's the relevant part of my main.py configuration:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI(
title="My Project",
openapi_url=f"/api/v1/openapi.json",
docs_url=f"/api/v1/docs",
redoc_url=f"/api/v1/redoc",
root_path="/myapp" # I added this to fix the error <-----------------
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/ping")
def ping():
return {"message": "pong"}
# Include other routers and setup
This is my dockerfile if it is useful:
FROM python:3.12.3-slim
ENV PYTHONUNBUFFERED 1
ENV APP_HOME=/home/app/web
ENV APP_DEPS=/home/app
RUN mkdir -p $APP_HOME
RUN apt-get update && apt-get install -y \
gcc \
g++ \
make \
python3-dev \
tzdata \
libpq-dev \
libffi-dev \
cmake \
wget \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
WORKDIR $APP_DEPS
COPY requirements.txt $APP_DEPS
RUN python -m pip install --upgrade pip
RUN pip install -r requirements.txt
WORKDIR $APP_HOME
COPY /src/ $APP_HOME
CMD ["uvicorn", "main:app", "--reload", "--host", "0.0.0.0", "--port", "8000"]
It seems the issue arises because FastAPI needs to know the root path for all routes when deployed behind a reverse proxy or API Gateway that adds a prefix to the URL.
Here's how I resolved it:
Set the root_path in FastAPI configuration: This tells FastAPI to prepend the given root path to all routes, ensuring that the OpenAPI documentation and other paths are correctly resolved.
app = FastAPI(
title="My Project",
openapi_url=f"/api/v1/openapi.json",
docs_url=f"/api/v1/docs",
redoc_url=f"/api/v1/redoc",
root_path="/myapp" # <------ This root_path fix the problem
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With