Search code examples
powershellazure-devops-rest-api

How to create Azure DevOps task via rest api


I wrote some PowerShell functions to help me create user stories a bit faster, and this all works great, but now I am stuck figuring out how to create Tasks for a User Story/Work Item, and obviously having them be assigned to a specific Work Item.

I also can't find any documentation describing this. I almost imagine that I need use the uri "https://dev.azure.com/$($Organisation)/$Project/_apis/wit/workitems/`$Task?api-version=5.1" but I can't see how to associate it with a work item as part of this, or after.

Can anyone help or point me at some actual documentation for this, please?

Edit: While looking for something else, I stumbled across this, but sadly that errors out for me, so it might be deprecated by now...

Edit; Thanks for the help everyone. This now works for me This is my code in case it becomes useful for someone some day in the future:

#96116 is the parent work item, 96113 the child task
$ContentType = "application/json-patch+json"
$Token = System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PersonalAccessToken)"))
$Header = @{Authorization = 'Basic ' + $Token;accept=$ContentType}
$uri = "https://dev.azure.com/$Organisation/$Project/_apis/wit/workitems/96113?api-version=6.1-preview.3"
$body= @'
[
  {
    "op": "add",
    "path": "/relations/-",
    "value": {
      "rel": "System.LinkTypes.Hierarchy-Reverse",
      "url": "https://dev.azure.com/$Organisation/$Project/_apis/wit/workitems/96113",
      "attributes": {
          "isLocked": false,
          "name": "Parent"
      }
    }
  }
]
'@
Invoke-RestMethod -Uri $uri -Method PATCH -Headers $Header -Body $Body -ContentType $contentType

Solution

  • You can follow the steps below to create a new Task, and link a specified User Story as the Parent of this new Task:

    1. Use the endpoint "Work Items - Create" to create the new Task.

    2. Use the endpoint "Work Items - Update" to link the specified User Story as the Parent.

      • Request URI
        PATCH https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{id}?api-version=7.1-preview.3
        
      • Required Header
        Content-Type: application/json-patch+json
        
      • Request Body
        [
          {
            "op": "add",
            "path": "/relations/-",
            "value": {
              "rel": "System.LinkTypes.Hierarchy-Reverse",
              // This is the URL of the linked parent work item.
              "url": "https://dev.azure.com/{organization}/{project}/_apis/wit/workItems/{parent work item ID}",
              "attributes": {
                  "isLocked": false,
                  "name": "Parent"
              }
            }
          }
        ]
        

    I have tested this method, it can work fine as expected.