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

[ENH] Make root_path for app configurable #154

Merged
merged 3 commits into from
Jan 23, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/api/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@

EnvVar = namedtuple("EnvVar", ["name", "value"])

ROOT_PATH = EnvVar(
"NB_FAPI_ROOT_PATH", os.environ.get("NB_FAPI_ROOT_PATH", "")
)
IS_FEDERATE_REMOTE_PUBLIC_NODES = EnvVar(
"NB_FEDERATE_REMOTE_PUBLIC_NODES",
os.environ.get("NB_FEDERATE_REMOTE_PUBLIC_NODES", "True").lower()
Expand Down
17 changes: 9 additions & 8 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from contextlib import asynccontextmanager

import uvicorn
from fastapi import FastAPI
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
from fastapi.responses import HTMLResponse, ORJSONResponse, RedirectResponse
Expand Down Expand Up @@ -34,6 +34,7 @@ async def lifespan(app: FastAPI):


app = FastAPI(
root_path=util.ROOT_PATH.value,
default_response_class=ORJSONResponse,
docs_url=None,
redoc_url=None,
Expand All @@ -51,15 +52,15 @@ async def lifespan(app: FastAPI):


@app.get("/", response_class=HTMLResponse)
def root():
def root(request: Request):
"""
Display a welcome message and a link to the API documentation.
"""
return """
return f"""
<html>
<body>
<h1>Welcome to the Neurobagel Federation API!</h1>
<p>Please visit the <a href="/docs">documentation</a> to view available API endpoints.</p>
<p>Please visit the <a href="{request.scope.get("root_path", "")}/docs">API documentation</a> to view available API endpoints.</p>
alyssadai marked this conversation as resolved.
Show resolved Hide resolved
</body>
</html>
"""
Expand All @@ -74,24 +75,24 @@ async def favicon():


@app.get("/docs", include_in_schema=False)
def overridden_swagger():
def overridden_swagger(request: Request):
"""
Overrides the Swagger UI HTML for the "/docs" endpoint.
"""
return get_swagger_ui_html(
openapi_url="/openapi.json",
openapi_url=f"{request.scope.get('root_path', '')}/openapi.json",
title="Neurobagel Federation API",
swagger_favicon_url=favicon_url,
)


@app.get("/redoc", include_in_schema=False)
def overridden_redoc():
def overridden_redoc(request: Request):
"""
Overrides the Redoc HTML for the "/redoc" endpoint.
"""
return get_redoc_html(
openapi_url="/openapi.json",
openapi_url=f"{request.scope.get('root_path', '')}/openapi.json",
title="Neurobagel Federation API",
redoc_favicon_url=favicon_url,
)
Expand Down
37 changes: 33 additions & 4 deletions tests/test_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,26 @@
import pytest
from fastapi import status

from app.main import app


@pytest.mark.parametrize(
"root_path",
"route",
["/", ""],
)
def test_root(test_app, set_valid_test_federation_nodes, root_path):
def test_root(test_app, set_valid_test_federation_nodes, route, monkeypatch):
"""Given a GET request to the root endpoint, Check for 200 status and expected content."""

response = test_app.get(root_path, follow_redirects=False)
monkeypatch.setattr(app, "root_path", "")
response = test_app.get(route, follow_redirects=False)

assert response.status_code == status.HTTP_200_OK
assert all(
substring in response.text
for substring in [
"Welcome to",
"Neurobagel",
alyssadai marked this conversation as resolved.
Show resolved Hide resolved
'<a href="/docs">documentation</a>',
'<a href="/docs">API documentation</a>',
]
)

Expand Down Expand Up @@ -61,3 +64,29 @@ def test_request_including_trailing_slash_fails(
"""
response = test_app.get(invalid_route)
assert response.status_code == status.HTTP_404_NOT_FOUND


@pytest.mark.parametrize(
"test_route,expected_status_code",
[("", 200), ("/fapi/v1", 200), ("/wrongroot", 404)],
)
def test_docs_work_using_defined_root_path(
test_app, test_route, expected_status_code, monkeypatch
):
"""
Test that when the API root_path is set to a non-empty string,
the interactive docs and OpenAPI schema are only reachable with the correct path prefix
(e.g., mimicking access through a proxy) or without the prefix entirely (e.g., mimicking local access or by a proxy itself).

Note: We test the OpenAPI schema as well because when the root path is not set correctly,
the docs break from failure to fetch openapi.json.
(https://fastapi.tiangolo.com/advanced/behind-a-proxy/#proxy-with-a-stripped-path-prefix)
"""

monkeypatch.setattr(app, "root_path", "/fapi/v1")
docs_response = test_app.get(f"{test_route}/docs", follow_redirects=False)
schema_response = test_app.get(
f"{test_route}/openapi.json", follow_redirects=False
)
assert docs_response.status_code == expected_status_code
assert schema_response.status_code == expected_status_code
Loading