Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI multiple routes bound to same function. How to know which one was requested

Tags:

python

fastapi

Let's say I have 2 routes pointing to the same function

from fastapi import FastApi

app = FastApi()

@app.get('/api/')
@app.get('/api/test')
def main_route():
    ...

Both routes will call main_route function, but I want to know which route was used. Query parameters shouldn't be used in there. I was thinking of using request object but I want to know if there is a simpler solution for that.

like image 903
Aleksander Ikleiw Avatar asked Dec 30 '25 21:12

Aleksander Ikleiw


1 Answers

Definitely use the Request object here. You can run the below code as-is.

from fastapi import FastAPI, Request

app = FastAPI()

@app.get('/api')
@app.get('/api/test')
def main_route(request: Request):
    return {"Called from": request.url.path}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
like image 179
JarroVGIT Avatar answered Jan 01 '26 14:01

JarroVGIT