An Azure service that provides a hybrid, multi-cloud management platform for APIs.
Hi @Nayna Morekar Thank you for reaching out to Microsoft Q&A.
I have reproduced your issue and was able to attach the Attachment in the workitem:
To attach any attachment in work item, You need to use two API's
- https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/attachments/create?view=azure-devops-rest-7.1&tabs=HTTP#upload-a-text-file
- https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work-items/update?view=azure-devops-rest-7.1&tabs=HTTP#add-an-attachment
Make sure you have Read, Write and Manage permission assigned to the PAT token.
I have used below Powershell code to call both the API's and was able to attach the attachment successfully, I am adding the txt file content in the code itself and creating an attachment then updating it to work item:
# ----------------------------
# Inputs
# ----------------------------
$org = "xxxxxxx"
$project = "xxxxxxxx" # has a space -> must be URL-encoded
$pat = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
$apiVersion = "7.1"
$fileName = "xxxxxxxttachment.txt"
$textToUpload = "Uxxxxxxx xxxxx xxxx"
# ----------------------------
# Helpers
# ----------------------------
$projectEncoded = [uri]::EscapeDataString($project)
$basicAuth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$pat"))
$headers = @{
Authorization = "Basic $basicAuth"
}
# ----------------------------
# 1) Upload attachment (POST)
# ----------------------------
$uploadUrl = "https://dev.azure.com/$org/$projectEncoded/_apis/wit/attachments?fileName=$fileName&api-version=$apiVersion"
Write-Host "UPLOAD URL => $uploadUrl"
# Send as octet-stream bytes
$bytes = [Text.Encoding]::UTF8.GetBytes($textToUpload)
$uploadResp = Invoke-RestMethod `
-Uri $uploadUrl `
-Method Post `
-Headers $headers `
-ContentType "application/octet-stream" `
-Body $bytes
$attachmentUrl = $uploadResp.url
Write-Host "Attachment uploaded. URL => $attachmentUrl"
# ----------------------------
# 2) Attach to work item (PATCH)
# IMPORTANT: Use a literal JSON Patch array string to avoid PowerShell JSON quirks.
# 4 below is the workitemID
$patchUrl = "https://dev.azure.com/$org/$projectEncoded/_apis/wit/workitems/4?api-version=$apiVersion"
Write-Host "PATCH URL => $patchUrl"
$patchBody = @"
[
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "AttachedFile",
"url": "$attachmentUrl",
"attributes": {
"comment": "Spec for the work"
}
}
}
]
"@
$patchResp = Invoke-RestMethod `
-Uri $patchUrl `
-Method Patch `
-Headers $headers `
-ContentType "application/json-patch+json" `
-Body $patchBody
Write-Host "Done. Work item updated. New rev => $($patchResp.rev)"
Output: