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

使用requests.post向API服务器新增条目失败求助

问题分析与解决方案

1. 核心错误点排查

  • 日期格式无效:代码中manufacturedDate字段值为"2022.002.20",月份部分002不符合合法日期规则(有效月份范围为01-12),这会直接触发API的格式校验失败。
  • 数据类型不匹配:unitPrice和quantity被设置为字符串类型("1020"、"200"),但这类代表金额、数量的字段,绝大多数API会要求传入数值类型(整数/浮点数),字符串类型会导致数据解析错误。

2. 关键排查步骤

取消注释代码中的print(response.json()),打印API返回的具体错误信息——这是定位问题最直接的方式,比仅查看状态码能获取更多有效线索。同时建议核对课程提供的API文档,确认字段的格式、类型要求。

修正后的代码

import requests
BASE_URL = 'http://host1.open.uom.lk:8080'
product_entity = {
    "products": {
        "product": {
            "productName": "Araliya Basmathi Rice",
            "description": "White Basmathi Rice imported from Pakistan. High-quality rice with extra fragrance. Organically grown.",
            "category": "Rice",
            "brand": "CIC",
            "expiredDate": "2023.02.04",
            "manufacturedDate": "2022.02.20",  # 修正月份格式
            "batchNumber": "324567",
            "unitPrice": 1020,  # 改为数值类型
            "quantity": 200,  # 改为数值类型
            "createdDate": "2022.02.24"
        }
    }
}
response = requests.post(f"{BASE_URL}/products", json=product_entity)
print(response.status_code)
print(response.json())  # 打印错误详情辅助排查

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:10:13