Bad Request Error when creating work item using Azure Devops API

621 Views Asked by At

I am a beginner in using Azure Devops and in need of expert's help or anyone who has/had experience dealing with ADO API. I am trying to create work item from azure pipeline using the API. I am able to get it done using Postman but the script didn't work in the azure pipeline itself.

Here my code:

$pat = "xxxxx"  
$Cred = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$pat")) 
$headers = @{
       "Authorization" = ("Basic {0}" -f $Cred)
      }
$url = "https://dev.azure.com/xx/yy/_apis/wit/workitems/`$Task?/api-version=7.0"
      [HashTable]$body = @{  
        "op" = "add";
        "path" = "/fields/System.Title";
        "from" = "$null";
        "value" = "Test Task"
      }
  $bugJson = ConvertTo-Json -InputObject $body -AsArray

Write-Host "$url"
          try {
          Write-Host "Making API request..."
          $response = Invoke-RestMethod -uri $url -Method POST -Headers $headers -Body $bugJson   -ContentType application/json-patch+json
          Write-Host "Inside try block. Attempting to create the work item..."
          Write-Host "API request completed."
          Write-Host "Bug work item created with ID: $($response.id)"
      } catch {
          Write-Host "Inside catch block. An error occurred while creating the work item."  
          Write-Host "Failed to create bug work item. Error: $($_.Exception)"
          Write-Host "Failed to create bug work item. Error: $($_.Exception.message)"
          Write-Host "Response: $($response | ConvertTo-Json -Depth 10)"
      }`

Here the output in the log:

Making API request...
Inside catch block. An error occurred while creating the work item.
Failed to create bug work item. 
Error: Microsoft.PowerShell.Commands.HttpResponseException: Response status code does not indicate success: 400 (Bad Request).
   at System.Management.Automation.MshCommandRuntime.ThrowTerminatingError(ErrorRecord errorRecord)
Failed to create bug work item. Error: Response status code does not indicate success: 400 (Bad Request).
Response: null

My PAT has full access. I am the admin of the project.

I referred to here and it is not working either: https://developercommunity.visualstudio.com/t/error-creating-work-items-via-az-devops-api-and-po/1155973

I referred to the Microsoft documentation page as well but none is working. Appreciate everyone helps and opinion.

1

There are 1 best solutions below

1
YK1 On

It is just a syntax error in your url. Remove the forward slash / right after the query string ?:

Here is the right url:

$url = "https://dev.azure.com/xx/yy/_apis/wit/workitems/`$Task?api-version=7.0"