jsonazure-devopsazure-devops-rest-api

ADO: upload an attachment to Azure DevOps via HTTP REST request


We're using ADO Server 2019 and as part of a larger project I need to upload some emails to the ADO environment to attach to work items. I've already figured out that you first need to upload the attachment, pass over the attachment ID to the work item patch request and add the relationship from the work item end however what I can't for the life of me figure out is where to pick the actual email or any item up to upload.

The example that's given within the MS docs shows you how to post an upload but it uploads nothing, it just creates a blank page.

POST https://{instance}/fabrikam/_apis/wit/attachments?fileName=textAsFileAttachment.txt&api-version=5.0

A body for the request needs to be built to define where the attachment is from what I can gather however there isn't any kind of documentation around this for simply posting it via HTTP.

We're using Blue Prism so using C# is an option but not ideal.

Thanks in advance.


Solution

  • Please follow the steps below:

    1. Upload a text file

      POST https://{instance}/fabrikam/_apis/wit/attachments?fileName=textAsFileAttachment.txt&api-version=5.0
      

    Request Body: "User text content to upload"

    1. You will get a response like:

      {
         "id": "6b2266bf-a155-4582-a475-ca4da68193ef",
         "url": "https://fabrikam:8080/tfs/_apis/wit/attachments/6b2266bf-a155-4582-a475-ca4da68193ef?fileName=textAsFileAttachment.txt"
       }
      

      Copy this url from the response.

    2. Add an attachment to work items:

      POST https://{instance}/fabrikam/_apis/wit/attachments?fileName=textAsFileAttachment.txt&api-version=5.0
      

      Request body:

      [
         {
           "op": "add",
           "path": "/relations/-",
           "value": {
             "rel": "AttachedFile",
             "url": "https://fabrikam:8080/tfs/_apis/wit/attachments/6b2266bf-a155-4582-a475-ca4da68193ef?fileName=textAsFileAttachment.txt",
             "attributes": {
               "comment": "Spec for the work"
             }
           }
         }
      ]
      

      Replace the url of the request body.