Question mark in POST method using FastAPI returns 404 error

Viewed 197

Could you please explain to me why in FastAPI the following works:

@app.post("/items/v1/cards{sku}")
async def create_item(sku: str):
    return {"status":200,"sku":sku}  # returns status:200 and sku 

but, the same endpoint with questionmark in it like the one given below does not?

@app.post("/items/v1/cards?{sku}")
async def create_item(sku: str):
    return {"sku":sku}  # returns 404
1 Answers

In the first code snippet, you define the parameter as a Path parameter and works as expected. In the second one, however, you attempt to pass a Query parameter in the wrong way. As per the documentation:

When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as "query" parameters.

Hence, your endpoint should look like this:

@app.post("/items/v1/cards")
async def create_item(sku: str):
    return {"sku":sku}

The query is the set of key-value pairs that go after the ? in a URL, separated by & characters.

For example, in the URL:

http://127.0.0.1:8000/items/v1/cards?sku=something
Related