Skip to content
This repository was archived by the owner on May 29, 2026. It is now read-only.

Commit 75d6a5a

Browse files
committed
fix: handle Starlette routes in FastAPI middleware
This commit changes the FastAPI middleware so that the `"route"` info is now optional. If it is not present, the SQL comment will not have the controller/route info. This info is always present in FastAPI routes. However, Starlette-based routes (FastAPI can mount Starlette apps as sub-applications) do not and would crash when the middleware tried to extract the information. Fixes #133
1 parent 0c309fc commit 75d6a5a

3 files changed

Lines changed: 25 additions & 1 deletion

File tree

python/sqlcommenter-python/google/cloud/sqlcommenter/fastapi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,5 +95,5 @@ def _get_fastapi_route(fastapi_app: FastAPI, scope) -> Optional[Route]:
9595
# and return the route name if found.
9696
match, child_scope = route.matches(scope)
9797
if match == Match.FULL:
98-
return child_scope["route"]
98+
return child_scope.get("route")
9999
return None

python/sqlcommenter-python/tests/fastapi/app.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
from fastapi import FastAPI, status
44
from fastapi.responses import JSONResponse
5+
from starlette.applications import Starlette
56
from starlette.exceptions import HTTPException as StarletteHTTPException
7+
from starlette.routing import Route
68

79
from google.cloud.sqlcommenter.fastapi import SQLCommenterMiddleware, get_fastapi_info
810

@@ -27,3 +29,15 @@ async def custom_http_exception_handler(request, exc):
2729
status_code=status.HTTP_404_NOT_FOUND,
2830
content=get_fastapi_info(),
2931
)
32+
33+
34+
def starlette_endpoint(_):
35+
return JSONResponse({"from": "starlette"})
36+
37+
38+
starlette_subapi = Starlette(routes=[
39+
Route("/", starlette_endpoint),
40+
])
41+
42+
43+
app.mount("/starlette", starlette_subapi)

python/sqlcommenter-python/tests/fastapi/tests.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,13 @@ def test_get_fastapi_info_in_404_error_context(client):
5353

5454
def test_get_fastapi_info_outside_request_context(client):
5555
assert get_fastapi_info() == {}
56+
57+
58+
def test_get_openapi_does_not_throw_an_error(client):
59+
resp = client.get(app.docs_url)
60+
assert resp.status_code == 200
61+
62+
63+
def test_get_starlette_endpoints_does_not_throw_an_error(client):
64+
resp = client.get("/starlette")
65+
assert resp.status_code == 200

0 commit comments

Comments
 (0)