Question mark in POST method using FastAPI returns 404 error
Asked Answered
S

1

1

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
Stubbed answered 30/4, 2022 at 10:19 Comment(0)
D
0

In the first code snippet, you defined the parameter as a Path parameter and worked as expected.

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

URL Example:

http://127.0.0.1:8000/items/v1/cards/something

In the second one, however, you attempted 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.

URL Example:

http://127.0.0.1:8000/items/v1/cards?sku=something
Dorser answered 30/4, 2022 at 11:17 Comment(1)
Ohk, thank you @Dorser for explaining it . I modified the endpoint as you suggested and it works, thank you for your time.Stubbed

© 2022 - 2024 — McMap. All rights reserved.