with FastAPI, is it possible to have default path parameters?

Question:

my question is, how can i get a default value for the path parameter to work?

for the following endpoint:

from FastAPI import Path as fPath

@app.get("/users/{code}")
async def get_user(code: str = fPath("hellomotto", regex=r'hello.*')):
    return {"code": code}

now, if i visit localhost:666/users/helloworld it will give me a good response:

{"code": "helloworld"}

however, if i try to go to localhost:666/users/, it will give me a response of { "detail": "Not Found" }

is there a way for it to instead return {"code": "hellomotto"} as a default in case the user does not type something like localhost:666/users/hellomotto

of course i can just have an endpoint for /users/ but figured i could set a default…

edit: also tried default="hellomoto"
edit2: when i try with query parameters it does resort to the default value…

Asked By: avnav99

||

Answers:

localhost:666/users/ matches with /users/ only, but it will never match /users/{something}. That’s why FastAPI is returning 404.

However, getting a user by default in that way, doesn’t sound to me like a good API design. Usually, a GET /something/ will return a list of something, instead of a specific default element.

What you can do is something like this:

def _get_user(code: str):
    return {"code": code}

@app.get("/users/default")
async def get_user_by_default():
    return _get_user("hellomotto")

@app.get("/users/{code}")
async def get_user_by_code(code: str = Path(..., regex=r'hello.*')):
    return _get_user(code)

If you still want to do it with a missing code path parameter, you could use /users/ instead of /users/default but I still think it’s not a good idea as it’s not explicit enough. Besides that, something like that should help to manage that default use case.

Answered By: JonDoe297
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.