FastAPI:通过 GET 发送请求正文时出错
FastAPI: Error by sending Request Body trough GET
我正在更新我使用 Python 和 FastAPI 编码的一些 API。在实际版本中,我使用 Query Paramenters 发送信息,但现在我想尝试使用 Request Body 发送数据,但是代码似乎不起作用。
您可以在下面看到 服务器端 的代码示例,其中 FastAPI 应该 return 我发送的文本(对于这个例子只有“string_to_show" 信息,但在实际项目中会有更多字段)。我知道那是基本代码,但这只是一个示例。
from fastapi import FastAPI, Path, Query
from pydantic import BaseModel
import uvicorn
app = FastAPI()
class req_body(BaseModel):
string_to_show:str
@app.get("/test/")
def scraper_shield(payload:req_body):
request_feedback = str(payload.string_to_show)
return request_feedback
if __name__ == "__main__":
uvicorn.run(app)
在客户端我正在使用这段代码,它只是将负载发送到服务器。
import requests
payload = {'string_to_show':'Python is great!'}
r = requests.get('http://127.0.0.1:8000/test/', params=payload)
print(r.text)
发送请求时,我应该得到字符串 "Python is Great!" 但我却收到 一些错误,在客户端和服务器消息下方:
- CLIENT: {"detail":[{"loc":["body"],"msg":"必填字段","type":"value_error.missing"}]}
- SERVER: "GET /test/?string_to_show=Python+is+great%21 HTTP/1.1" 422 不可处理实体
您在使用时将参数作为查询字符串发送
r = requests.get('http://127.0.0.1:8000/test/', params=payload)
。你必须改用
r = requests.get('http://127.0.0.1:8000/test/', json=payload)
这将创建一个请求正文并正确发送它。这也是您从错误中看到的,它基本上告诉您缺少所需的正文。
GET 方法不应该有 body.
https://dropbox.tech/developers/limitations-of-the-get-method-in-http
POST 方法就是为此而设计的。
如果您真的需要使用 GET 进行一些强大的参数化(但我真的会重新考虑),请考虑将它们放入自定义 header(s).
我正在更新我使用 Python 和 FastAPI 编码的一些 API。在实际版本中,我使用 Query Paramenters 发送信息,但现在我想尝试使用 Request Body 发送数据,但是代码似乎不起作用。
您可以在下面看到 服务器端 的代码示例,其中 FastAPI 应该 return 我发送的文本(对于这个例子只有“string_to_show" 信息,但在实际项目中会有更多字段)。我知道那是基本代码,但这只是一个示例。
from fastapi import FastAPI, Path, Query
from pydantic import BaseModel
import uvicorn
app = FastAPI()
class req_body(BaseModel):
string_to_show:str
@app.get("/test/")
def scraper_shield(payload:req_body):
request_feedback = str(payload.string_to_show)
return request_feedback
if __name__ == "__main__":
uvicorn.run(app)
在客户端我正在使用这段代码,它只是将负载发送到服务器。
import requests
payload = {'string_to_show':'Python is great!'}
r = requests.get('http://127.0.0.1:8000/test/', params=payload)
print(r.text)
发送请求时,我应该得到字符串 "Python is Great!" 但我却收到 一些错误,在客户端和服务器消息下方:
- CLIENT: {"detail":[{"loc":["body"],"msg":"必填字段","type":"value_error.missing"}]}
- SERVER: "GET /test/?string_to_show=Python+is+great%21 HTTP/1.1" 422 不可处理实体
您在使用时将参数作为查询字符串发送
r = requests.get('http://127.0.0.1:8000/test/', params=payload)
。你必须改用
r = requests.get('http://127.0.0.1:8000/test/', json=payload)
这将创建一个请求正文并正确发送它。这也是您从错误中看到的,它基本上告诉您缺少所需的正文。
GET 方法不应该有 body. https://dropbox.tech/developers/limitations-of-the-get-method-in-http
POST 方法就是为此而设计的。 如果您真的需要使用 GET 进行一些强大的参数化(但我真的会重新考虑),请考虑将它们放入自定义 header(s).