Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for ASGI root_path for openapi docs #1199

Merged
merged 11 commits into from
Jun 11, 2020
Next Next commit
Use ASGI root_path when it is provided and openapi_prefix is empty.
  • Loading branch information
iksteen committed Mar 31, 2020
commit 5fad17371470b819f4b17c736aaba31b8150c80f
22 changes: 16 additions & 6 deletions fastapi/applications.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def __init__(
self.description = description
self.version = version
self.openapi_url = openapi_url
self.openapi_prefix = openapi_prefix.rstrip("/")
self._openapi_prefix = openapi_prefix.rstrip("/")
self.docs_url = docs_url
self.redoc_url = redoc_url
self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url
Expand All @@ -87,33 +87,42 @@ def __init__(
self.openapi_schema: Optional[Dict[str, Any]] = None
self.setup()

def openapi(self) -> Dict:
def get_openapi_prefixed(self, req: Request, path: str = "") -> str:
return (self._openapi_prefix or req.scope.get("root_path", "")) + path

def openapi(self, openapi_prefix: str) -> Dict:
if not self.openapi_schema:
self.openapi_schema = get_openapi(
title=self.title,
version=self.version,
openapi_version=self.openapi_version,
description=self.description,
routes=self.routes,
openapi_prefix=self.openapi_prefix,
openapi_prefix=openapi_prefix,
)
return self.openapi_schema

def setup(self) -> None:
if self.openapi_url:

async def openapi(req: Request) -> JSONResponse:
return JSONResponse(self.openapi())
openapi_prefix = self.get_openapi_prefixed(req)
return JSONResponse(self.openapi(openapi_prefix))

self.add_route(self.openapi_url, openapi, include_in_schema=False)
openapi_url = self.openapi_prefix + self.openapi_url
if self.openapi_url and self.docs_url:

async def swagger_ui_html(req: Request) -> HTMLResponse:
openapi_url = self.get_openapi_prefixed(req, self.openapi_url)
oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url
if oauth2_redirect_url:
oauth2_redirect_url = self.get_openapi_prefixed(
req, oauth2_redirect_url
)
return get_swagger_ui_html(
openapi_url=openapi_url,
title=self.title + " - Swagger UI",
oauth2_redirect_url=self.swagger_ui_oauth2_redirect_url,
oauth2_redirect_url=oauth2_redirect_url,
init_oauth=self.swagger_ui_init_oauth,
)

Expand All @@ -132,6 +141,7 @@ async def swagger_ui_redirect(req: Request) -> HTMLResponse:
if self.openapi_url and self.redoc_url:

async def redoc_html(req: Request) -> HTMLResponse:
openapi_url = self.get_openapi_prefixed(req, self.openapi_url)
return get_redoc_html(
openapi_url=openapi_url, title=self.title + " - ReDoc"
)
Expand Down