Microsoft Azure API在使用python创建工作项时返回错误

4smxwvx5  于 2023-06-24  发布在  Python
关注(0)|答案(1)|浏览(126)

我正在尝试在Azure Board中创建简单工作项
我用python来做这个。下面是我的代码:

def post_work_item():
    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, timeout=10800).json()
    print(json.dumps(response, indent=2, sort_keys=True))

我在遵循微软官方文档
https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work-items/create?view=azure-devops-rest-7.0&tabs=HTTP
但它返回的是:

{
  "$id": "1",
  "errorCode": 0,
  "eventId": 3000,
  "innerException": null,
  "message": "You must pass a valid patch document in the body of the request.",
  "typeKey": "VssPropertyValidationException",
  "typeName": "Microsoft.VisualStudio.Services.Common.VssPropertyValidationException, Microsoft.VisualStudio.Services.Common"
}

我不知道出了什么问题。有谁能帮我把这个弄好吗?我发现了很多类似的案例,但没有一个使用python,当我试图调整解决方案时,我总是失败。

klr1opcd

klr1opcd1#

我尝试在下面的Python代码中在Azure Devops中创建工作项。
代码:

import json
import requests

PAT = "<personal-access-token>" 
request_url = "https://dev.azure.com/<organization-name>/<project-name>/_apis/wit/workitems/$Task?api-version=5.0"

try:
    flds = [
        {"op": "add", "path": "/fields/System.Title", "value": "Sample task"}
    ]
    json_data = json.dumps(flds)
    headers = {
        "Content-Type": "application/json-patch+json"
    }
    response = requests.patch(request_url, data=json_data, headers=headers, auth=("", PAT))
    response.raise_for_status()
    
    if response.status_code == 200:
            print("Work item created successfully.")
    else:
            print("Error creating work item:", response.json())

except requests.exceptions.RequestException as ex:
    pass

输出:
运行成功如下:

在Azure Devops中成功创建的工作项如下,

参考:

选中此link以创建Azure Devops个人访问令牌。

相关问题