gipcu
gipcu

Reputation: 321

Microsoft Azure API returns error when creating Work Item using Python

I am trying to create simple work item in Azure Board
I am using Python to do this. Here is my code:

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))

I was following official Microsoft Documentation
(https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work-items/create?view=azure-devops-rest-7.0&tabs=HTTP)
But all it returns is:

{
  "$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"
}

I have no idea what is wrong. Could anyone help me make this work? I found plenty similar cases but none of them use python and when I tried to adjust solutions I always failed.

Upvotes: 1

Views: 232

Answers (1)

Dasari Kamali
Dasari Kamali

Reputation: 3649

I tried below python code to create a work item in Azure Devops.

Code:

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

Output:

It runs successfully as below,

enter image description here

The work item created successfully in Azure Devops as below,

enter image description here

Reference:

Check this link to create Azure Devops personal access tokens.

Upvotes: 1

Related Questions