Browse Source

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": "<root_path>"}] 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
pull/15484/head
阿泥豆 1 month ago
parent
commit
7131c06482
  1. 9
      fastapi/applications.py

9
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)

Loading…
Cancel
Save