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

FastAPI接收JSON列表报解析错误及422错误的问题排查

问题分析与解决

1. 直接用list[str]/set[str]作为接口参数的问题

FastAPI默认会把这类参数识别为查询参数,而非请求体中的JSON数据,所以发送JSON请求体时会触发解析失败,返回400错误。需要显式用Body()标记参数,指定它来自请求体。

正确代码示例

from fastapi import FastAPI, Body

app = FastAPI()

@app.post("/urls-list")
async def receive_urls(urls: list[str] = Body(...)):
    return {"received_urls": urls}

2. 使用Pydantic BaseModel的问题

422错误大概率是请求格式问题:要么字段名不匹配,要么发送请求时没正确设置Content-Type: application/json。

正确代码示例

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class UrlsRequest(BaseModel):
    urls: list[str]  # 改用set[str]会自动去重,需注意集合是无序的

@app.post("/urls-model")
async def receive_urls_model(request: UrlsRequest):
    return {"received_urls": request.urls}

3. 正确的requests测试代码

必须确保用json参数传递数据(会自动设置正确的请求头),不要用data参数传JSON字符串:

import requests

# 测试Body标记的接口
response1 = requests.post(
    "http://localhost:8000/urls-list",
    json={"urls": ["https://www.website.com/", "https://www.anotherwebsite.com"]}
)
print(response1.status_code, response1.json())

# 测试BaseModel的接口
response2 = requests.post(
    "http://localhost:8000/urls-model",
    json={"urls": ["https://www.website.com/", "https://www.anotherwebsite.com"]}
)
print(response2.status_code, response2.json())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:25:41