使用Python调用Microsoft Azure API创建Work Item时返回错误
解决Azure DevOps Work Item创建的Patch文档错误
你的代码存在三个关键问题,导致返回"You must pass a valid patch document in the body of the request"错误:
- 未传递请求体数据:
requests.post调用没有把定义好的data作为请求体发送给API - Patch格式错误:Azure DevOps的Work Item创建API要求传入JSON Patch格式的数组,而非单个字典
- 缺少必要的请求头:需要设置
Content-Type: application/json-patch+json,否则服务端无法识别请求体格式
修正后的完整代码
import requests import json # 请确保headers已包含认证信息(比如Authorization: Basic <base64编码的PAT>) headers = { "Content-Type": "application/json-patch+json", "Authorization": "Basic <你的Base64编码PAT>" } def post_work_item(): # Patch文档必须是数组格式 data = [ { "op": "add", "path": "/fields/System.Title", "value": "Sample task" } ] response = requests.post( url="https://dev.azure.com/YYYYYYY/XXXXXXX/_apis/wit/workitems/$Task?api-version=7.0", headers=headers, json=data, # 用json参数自动序列化并设置正确的Content-Type timeout=10800 ).json() print(json.dumps(response, indent=2, sort_keys=True)) post_work_item()
关键修改说明
- Patch文档改为数组:JSON Patch规范要求传入操作数组,即使只有一个操作也需要用
[]包裹 - 添加请求体传递:通过
requests.post的json参数传入数据,该参数会自动将Python对象序列化为JSON字符串,并设置正确的Content-Type;也可以手动用data=json.dumps(data),但需确保headers里已指定Content-Type - 确保认证头正确:
headers必须包含有效的认证信息,比如使用个人访问令牌(PAT)时,需要将PAT转换为Base64编码,格式为Basic <base64编码的"用户名:PAT">
内容的提问来源于stack exchange,提问作者gipcu
相关产品推荐
相关产品推荐

