使用Python调用Redmine REST API提交工单返回422错误如何解决
问题原因与解决方案
错误根因如下:
- 未指定请求的
Content-Type为application/json,Redmine无法识别传入的JSON结构,会判定所有业务字段为空 - JSON配置中存在拼写错误:
projet_id字段拼写错误,正确应为project_id,导致Redmine无法读取到项目ID关联信息 - 新增场景下无需传入
id字段:id是Redmine创建issue时自动生成的系统字段,主动提交会触发逻辑冲突。如果你的需求是更新已有的ID为2的issue,需要将请求方法改为PUT,请求地址替换为http://localhost:3000/issues/2.json
修正后代码示例
import requests import json username = "x" password = "x" # 新建issue用该地址 url = "http://localhost:3000/issues.json" # 若为更新ID为2的issue,替换为下面的地址,后续请求方法改为put # url = "http://localhost:3000/issues/2.json" with open('rest.json', 'r', encoding='utf-8') as f: issue_data = json.load(f) headers = { "Content-Type": "application/json" } # 新建场景用post response = requests.post( url, auth=(username, password), json=issue_data, headers=headers ) # 更新场景用put # response = requests.put( # url, # auth=(username, password), # json=issue_data, # headers=headers # ) print(response.status_code) print(response.text)
修正后JSON配置(新建issue场景)
{ "issue" : { "project_id" : 1, "tracker_id" : 1, "priority_id" :1, "status_id" : 1, "author_id" : 1, "subject" : "Subject changed", "description": "The subject was changed", "category_id" :1, "assigned_to_id" : 1 } }
内容的提问来源于stack exchange,提问作者Ōkami
相关产品推荐
相关产品推荐

