POST 方法中的问号使用 FastAPI returns 404 错误
Question mark in POST method using FastAPI returns 404 error
能否请您向我解释一下为什么在 FastAPI 中可以执行以下操作:
@app.post("/items/v1/cards{sku}")
async def create_item(sku: str):
return {"status":200,"sku":sku} # returns status:200 and sku
但是,下面给出的带有问号的相同端点不是吗?
@app.post("/items/v1/cards?{sku}")
async def create_item(sku: str):
return {"sku":sku} # returns 404
在第一个代码片段中,您将参数定义为 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.
因此,您的端点应如下所示:
@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:
http://127.0.0.1:8000/items/v1/cards?sku=something
能否请您向我解释一下为什么在 FastAPI 中可以执行以下操作:
@app.post("/items/v1/cards{sku}")
async def create_item(sku: str):
return {"status":200,"sku":sku} # returns status:200 and sku
但是,下面给出的带有问号的相同端点不是吗?
@app.post("/items/v1/cards?{sku}")
async def create_item(sku: str):
return {"sku":sku} # returns 404
在第一个代码片段中,您将参数定义为 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.
因此,您的端点应如下所示:
@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:
http://127.0.0.1:8000/items/v1/cards?sku=something