Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fastapi post method call with and without trailing slashes

I was trying to write a fastapi post method as:

@app.post('/method/final_path/', tags=['method/final_path'])

When i do a postman call as https://......./method/final_path/
I get the expected result, but if the call is changed to https://......./method/final_path
I get 405-method not allowed.

According to FastAPI docs, the trailing slashes shouldn't matter, so ideally

@app.post('/method/final_path/', tags=['method/final_path'])
@app.post('/method/final_path', tags=['method/final_path'])

with postman calls:

  • https://......./method/final_path/
  • https://......./method/final_path

all the above 4 combinations should give the same result. Then what am I doing wrong?

Versions:
fastapi-0.63
starlette-0.13.6

Thanks in advance.

like image 656
anik jha Avatar asked Apr 06 '26 08:04

anik jha


2 Answers

Try using APIRouter to define the route instead of directly using the app. The APIRouter has redirect_slashes set to True by default.

like image 156
Rafiqul Hasan Avatar answered Apr 08 '26 22:04

Rafiqul Hasan


This is not actual problem already, but helpful insight here.

FastAPI released feature with global redirect_slashes and its True by default. It will redirect to your rout you defined in the code.

  1. Case define without slash

@app.get("/route_slash_example")

http://127.0.0.1:8000/route_slash_example/ will be redireceted to http://127.0.0.1:8000/route_slash_example

  1. Case define with slash

@app.get("/route_slash_example/")

http://127.0.0.1:8000/route_slash_example will be redirected to http://127.0.0.1:8000/route_slash_example/

like image 40
Dmitri Galkin Avatar answered Apr 08 '26 21:04

Dmitri Galkin