MRPeasy API发送POST请求传参失败返回400错误如何解决
简要说明(TLDR)
开发API项目过程中,需要向MRPeasy发送请求更新部分字段,目前遇到的核心问题为请求携带的参数无法被服务端正确解析,每次请求均返回400状态码。
详细说明
MRPeasy官方接口文档为本次开发的核心参考资料,文档中提供了GET、更新类请求两个示例,其中GET请求调试、运行均正常,更新类请求始终调用失败,文档给出的示例命令如下:
# GET请求示例 curl -X "GET" "https://app.mrpeasy.com/rest/v1/items" \ -H 'Content-Type: application/json' \ -H 'api_key: xxxxxxxxxxxxx' \ -H 'access_key: xxxxxxxxxxxxx' # 更新请求示例 curl -X "PUT" "https://app.mrpeasy.com/rest/v1/items/5" \ -H 'Content-Type: application/json' \ -H 'api_key: xxxxxxxxxxxxx' \ -H 'access_key: xxxxxxxxxxxxx' \ -d '{"selling_price": "2.54"}'
参考示例编写的Python实现代码如下:
url = "https://app.mrpeasy.com/rest/v1/manufacturing-orders/69" headers = { "Content-Type": "application/json", "api_key": my_api_key, "access_key": my_access_key } print(requests.get(url, headers=headers).json()["custom_3338"]) url = "https://app.mrpeasy.com/rest/v1/manufacturing-orders/69" headers = { "Content-Type": "application/json", "api_key": my_api_key, "access_key": my_access_key } data = json.dumps({"custom_3338": "1654642800.0000000000"}) print(requests.post(url, headers=headers, data=data).status_code)
针对请求的data参数,已经尝试过以下多种传参格式,均未请求成功:
'{"custom_3338": "1654642800.0000000000"}' {"custom_3338": "1654642800.0000000000"} {"due_date": "1654642800.0000000000"} {"quantity": 3} '{"quantity": 3}'
问题原因与修复方案
你遇到400错误的核心原因有两个:
HTTP请求方法用错
文档里的更新示例明确使用PUT方法,而非POST。MRPeasy接口遵循标准RESTful规范:GET用于查询资源,POST用于新建资源,PUT用于更新已存在的指定资源。你要更新ID为69的制造订单,必须使用PUT方法发起请求,用POST会被服务端直接判定为非法请求返回400。传参方式存在隐患,容易触发序列化格式错误
使用Python requests库发JSON请求时,不需要手动调用json.dumps()把字典转成字符串,直接把字典传给请求的json参数即可,requests会自动完成序列化,同时自动设置正确的Content-Type请求头,避免手动转码时出现隐藏的格式错误。
修正后的可运行代码如下:
import requests url = "https://app.mrpeasy.com/rest/v1/manufacturing-orders/69" headers = { "api_key": my_api_key, "access_key": my_access_key } # 原有查询逻辑保持正常 print(requests.get(url, headers=headers).json()["custom_3338"]) # 修正后的更新请求 update_data = {"custom_3338": "1654642800.0000000000"} resp = requests.put(url, headers=headers, json=update_data) print(resp.status_code) # 后续如果还有报错,直接打印resp.text就能看到服务端返回的具体错误提示,不用盲目测试参数格式 # print(resp.text)
内容的提问来源于stack exchange,提问作者Greg Zybala
相关产品推荐
相关产品推荐

