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

使用Postman向FastAPI发送POST请求时出现422 ValidationError的原因

解决FastAPI POST请求返回422 Unprocessable Entity的问题

问题分析

你遇到的422错误核心来自两个方面:代码语法错误,以及Postman请求格式配置问题。

解决步骤

1. 修复代码中的语法错误

你的create_posts函数返回语句存在明显语法错误:

return  {"new_post":f"title:"[new_post.title]}

这里的f-string写法不符合Python语法规范,正确写法是用{}包裹需要插入的变量,示例如下:

@app.post("/createposts/")
def create_posts(new_post:Post):
    print(new_post.title)
    # 正确的f-string写法,拼接标题和内容
    return  {"new_post": f"title: {new_post.title}, content: {new_post.content}"}
    # 也可以直接返回模型的字典结构,更清晰
    # return {"new_post": new_post.dict()}

2. 检查Postman请求配置

FastAPI需要正确的请求头才能解析JSON格式的请求体,需确认以下两点:

  • 打开Postman的Headers标签,添加Content-Type键,值设置为application/json
  • 确认请求体选择raw格式,并且右侧下拉菜单选中JSON(而非Text或其他格式)

3. 验证请求体格式

确保请求体没有语法错误,比如多余逗号、引号不匹配等,你提供的示例请求体是正确的:

{
 "title":"a",
 "content":"b"
}

测试修复效果

修改代码并调整Postman配置后,重新发送POST请求,应该能得到正常响应,示例响应如下:

{
  "new_post": "title: a, content: b"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:50:22