pythonhttpfastapihttp-status-code-404query-string

Question mark in POST method using FastAPI returns 404 error


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 question mark 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

Solution

  • 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