我看到另一个问题的回复询问了同样的事情(链接:如何在 Azure DevOps 中使用 REST API 将工作项链接到拉取请求?),但是虽然 patch 命令将我的 PR 链接到我的工作项,我希望能够在发送 POST 请求以创建 PR 时附加现有工作项。我怎样才能实现这个目标?
我希望能够在发送 POST 请求以创建 PR 时附加现有工作项。
您可以在请求正文中定义
workItemRefs
,以在发送 POST 请求时将 PR 链接到工作项 Pull Requests - Create 以创建 PR。
这是示例 PowerShell 脚本
# Replace with your actual values
$organization = ""
$project = ""
$repository = ""
$sourceRefName = "refs/heads/feature-branch"
$targetRefName = "refs/heads/main"
$title = "My Pull Request"
$description = "This is a pull request"
$workItemId = "634"
$personalAccessToken = ""
# Create the JSON payload
$body = @{
sourceRefName = $sourceRefName
targetRefName = $targetRefName
title = $title
description = $description
workItemRefs = @(@{ id = $workItemId })
} | ConvertTo-Json
# Define the URL
$url = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/pullRequests?api-version=7.1"
# Send the POST request
$response = Invoke-RestMethod -Uri $url -Method Post -Body $body -ContentType "application/json" -Headers @{
Authorization = "Basic " + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$personalAccessToken"))
}
# Output the response
$response
这是示例 Python 脚本:
import requests
import json
import base64
# Replace with your actual values
organization = ""
project = ""
repository = ""
source_ref_name = "refs/heads/feature-branch"
target_ref_name = "refs/heads/main"
title = "My Pull Request"
description = "This is a pull request"
work_item_id = "634"
personal_access_token = ""
# Create the JSON payload
body = {
"sourceRefName": source_ref_name,
"targetRefName": target_ref_name,
"title": title,
"description": description,
"workItemRefs": [{"id": work_item_id}]
}
# Define the URL
url = f"https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repository}/pullRequests?api-version=7.1"
# headers
headers = {
"Authorization": "Basic " + base64.b64encode(f":{personal_access_token}".encode("ascii")).decode("ascii"),
"Content-Type": "application/json"
}
# Send the POST request
response = requests.post(url, headers=headers, data=json.dumps(body))
# Format and output the response
formatted_response = json.dumps(response.json(), indent=4)
print(formatted_response)
测试结果: