From 7131c064826dfd9bb1c12240b3d5a4190bc7e431 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E6=B3=A5=E8=B1=86?= <1243352777@qq.com> Date: Tue, 5 May 2026 19:43:31 +0800 Subject: [PATCH] Fix OpenAPI servers field missing when root_path_in_servers=True (#12246) When root_path_in_servers=True (default), the OpenAPI schema should always include a servers field. Previously, when no root_path was configured (or root_path was '/'), the servers key was entirely absent from the OpenAPI JSON output. This fix ensures: - servers=[{"url": "/"}] when root_path_in_servers=True and no custom servers or root_path are configured - servers=[{"url": ""}] when root_path is set - servers are omitted only when root_path_in_servers=False - Custom servers are preserved and root_path is prepended when applicable --- fastapi/applications.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/fastapi/applications.py b/fastapi/applications.py index 4af1146b0d..d5829ad03c 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -1104,7 +1104,14 @@ class FastAPI(Starlette): async def openapi(req: Request) -> JSONResponse: root_path = req.scope.get("root_path", "").rstrip("/") schema = self.openapi() - if root_path and self.root_path_in_servers: + if self.root_path_in_servers and "servers" not in schema: + if root_path: + schema = dict(schema) + schema["servers"] = [{"url": root_path}] + else: + schema = dict(schema) + schema["servers"] = [{"url": "/"}] + elif root_path and self.root_path_in_servers: server_urls = {s.get("url") for s in schema.get("servers", [])} if root_path not in server_urls: schema = dict(schema)