Skip to content

Commit 1411804

Browse files
committed
Python: Allow custom fastapi.APIRouter subclasses
1 parent d493cfd commit 1411804

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
lgtm,codescanning
2+
* Extended the modeling of FastAPI such that custom subclasses of `fastapi.APIRouter` are recognized.

python/ql/lib/semmle/python/frameworks/FastApi.qll

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ private module FastApi {
3333
module APIRouter {
3434
/** Gets a reference to an instance of `fastapi.APIRouter`. */
3535
API::Node instance() {
36-
result = API::moduleImport("fastapi").getMember("APIRouter").getReturn()
36+
result = API::moduleImport("fastapi").getMember("APIRouter").getASubclass*().getReturn()
3737
}
3838
}
3939

python/ql/test/library-tests/frameworks/fastapi/router.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# like blueprints in Flask
22
# see https://fastapi.tiangolo.com/tutorial/bigger-applications/
3+
# see basic.py for instructions for how to run this code.
34

45
from fastapi import APIRouter, FastAPI
56

@@ -30,4 +31,23 @@ async def items(): # $ requestHandler
3031
app.include_router(outer_router, prefix="/outer")
3132
app.include_router(items_router)
3233

33-
# see basic.py for instructions for how to run this code.
34+
# Using a custom router
35+
36+
class MyCustomRouter(APIRouter):
37+
"""
38+
Which automatically removes trailing slashes
39+
"""
40+
def api_route(self, path: str, **kwargs):
41+
path = path.rstrip("/")
42+
return super().api_route(path, **kwargs)
43+
44+
45+
custom_router = MyCustomRouter()
46+
47+
48+
@custom_router.get("/bar/") # $ routeSetup="/bar/"
49+
async def items(): # $ requestHandler
50+
return {"msg": "custom_router /bar/"} # $ HttpResponse
51+
52+
53+
app.include_router(custom_router)

0 commit comments

Comments
 (0)