6

Within a release pipeline a new Pull Requested is created using REST API.

How to link a specific (already existing) Work Item to the Pull Request using REST API?

In the current version (DevOps 2019) it is not supported to link Work Items using Pull Request API. (See also related community issue.)

lg2de
  • 616
  • 4
  • 16

1 Answers1

8

Using PowerShell the following snipped may help.

$requestUri = "$tfsCollectionUri/$teamProject/_apis/wit/workitems/$workItemId?api-version=5.0"
$json = '
[ {
  "op": "add",
  "path": "/relations/-",
  "value": {
    "rel": "ArtifactLink",
    "url": "$pullRequestArtifact",
    "attributes": { "name": "pull request" }
  }
} ]'
$response = Invoke-RestMethod -Uri $requestUri -UseDefaultCredentials -ContentType "application/json-patch+json" -Method Patch -Body $json

Note, $pullRequestArtifact needs to be set. You can get it e.g. from get request.

FIL
  • 1,148
  • 3
  • 15
  • 27
lg2de
  • 616
  • 4
  • 16
  • Great ! You could accept this answer. It will be helpful to other users. Thanks. – Kevin Lu-MSFT Dec 07 '20 at 05:17
  • I can "accept" my own answer. That is great. Maybe you can vote my question/answer if you think it is correct, @KevinLu-MSFT? – lg2de Dec 07 '20 at 08:24
  • 3
    Absolute hero. I had to make a few modifications (running on TFS 2018): `-Method Patch` instead of Post, and `api-version=4.1` instead of 5.0. And this info was missing from this for me: `$pullRequestArtifact = "vstfs:///Git/PullRequestId/$teamProject/$repositoryName/$pullRequestId"` – SvenS Dec 23 '20 at 14:20
  • 1
    Thanks, @SvenS, you are right. I forgot to mention because I did not BUILD the artifact URI but GET it from previous request. I edited the text to mention this. – lg2de Jan 04 '21 at 09:39
  • The pull request was added to the workitem. But unfortunatly, this does not add the wokritem to the pull request. And the pull request is still missing a workitem to complete the policy set on the branch. Manually it works both ways but not using the api – Mariusz Mar 08 '21 at 22:56
  • @Mariusz, this maybe a bug in your TFS/DevOps version. Normally such link is build automatically in both directions. My example works fine on DevOps 2019 (Dev17.M153.5). If it not works as expected you should ask at https://developercommunity.visualstudio.com/search?space=22 – lg2de Mar 10 '21 at 07:58
  • I'm on Dev18.M170.8. – Mariusz Apr 01 '21 at 20:57
  • @Ig2de Thanks, it works. The pull request was create with the VSTeam PSModule, I remove and changed it to API calls and the issue is not reproducible since. – Mariusz Aug 11 '21 at 17:50