You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python Requests向FastAPI提交含Unicode字符的JSON数据?

问题解决:FastAPI接收含Unicode字符的Pydantic模型时JSON解码失败

问题根源

出现JSON解码错误的核心原因是客户端请求的Content-Type设置不正确,且Unicode字符的编码处理未到位:

  • 使用requests.post的data参数传递model_dump_json()生成的JSON字符串时,requests默认不会设置Content-Type: application/json请求头,服务端无法识别这是JSON格式的数据。
  • 含Unicode字符的JSON字符串直接作为data传递时,编码方式不符合服务端的解析预期,最终导致JSON解码失败。

修复方案

方案1:使用requests的json参数(推荐)

requests的json参数会自动将Python字典序列化为JSON字符串,同时设置正确的Content-Type: application/json请求头,无需手动处理编码问题。

修改后的client.py代码:

from pydantic import BaseModel, Field
import requests

class exClass(BaseModel):
    id: int = Field(example=1)
    text: str = Field(example="Text example")

ex1 = exClass(id=1, text="working example")
ex2 = exClass(id=2, text="this’ will work now")
ex3 = exClass(id=3, text="🤗 <- also working now")

# 使用json参数,传入model_dump()生成的字典
r = requests.post("http://127.0.0.1:8000/example", json=ex1.model_dump())
print(r.text)
r = requests.post("http://127.0.0.1:8000/example", json=ex2.model_dump())
print(r.text)
r = requests.post("http://127.0.0.1:8000/example", json=ex3.model_dump())
print(r.text)

方案2:手动设置请求头和编码(仅作说明)

如果一定要用data参数传递JSON字符串,需要手动设置Content-Type请求头,并确保字符串以UTF-8编码传递:

headers = {"Content-Type": "application/json; charset=utf-8"}
r = requests.post(
    "http://127.0.0.1:8000/example",
    data=ex2.model_dump_json().encode("utf-8"),
    headers=headers
)

验证结果

修改后运行客户端,三个请求都会返回true,服务端能正常解析含Unicode字符的Pydantic模型。

内容的提问来源于stack exchange,提问作者fMinkel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 10:25:27