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

使用FastAPI发送POST请求报错value is not a valid dict,如何修复?

修复FastAPI POST请求的"value is not a valid dict"错误

问题原因

你遇到的错误源于两个问题:

  • 请求数据传递方式错误:用json.dumps(transaction)生成的字符串直接作为POST请求的data参数时,requests默认会把请求头设为application/x-www-form-urlencoded,FastAPI无法将这种格式解析为预期的JSON字典。
  • amount字段的值AAA是未定义变量,运行时会直接抛出NameError。

修复步骤

  • 改用requests.post的json参数传递字典:无需手动序列化字典,requests会自动将其转为JSON字符串,并设置正确的Content-Type: application/json请求头,FastAPI就能正常解析。
  • 为amount设置合法数值:把AAA替换成具体数字(比如150),避免变量未定义错误。

修改后的完整代码

import requests
import datetime

def main():
    time = datetime.datetime.now().isoformat()

    transaction = {
        "time": time,
        "sender": "COCOCOCO",
        "receiver": "AAAAAA",
        "amount": 150,  # 替换为具体数值
        "description": "Christmas Dinner Fee",
        "signature": "signature_sample"
    }

    url ="https://XXXXXX.deta.dev/transaction_pool/"
    res = requests.post(url, json=transaction)  # 直接传字典给json参数
    print(res.json())

if __name__ == "__main__":
    main()

补充说明

如果一定要手动使用json.dumps,也可以通过以下方式实现,但不如上面的方法简洁:

import json
# ... 其余代码不变
res = requests.post(url, data=json.dumps(transaction), headers={'Content-Type': 'application/json'})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:20:54