I try to get Pull Requests using Azure DevOps API. And I want to include associated work items or only work item ids.
I can get PRs using this URL. But the answer does not include any info about work items.
GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/pullrequests?api-version=7.1-preview.1
The other URL that you can see below that I can get work items per PR using it.
GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}/workitems?api-version=7.1-preview.1
But the count of list of PRs can be big. So I think it is not appropriate to call the second URL each one of them.
Is there any better way to get work items with PR?
If you would like to get for one specific pull request and its associated work items, you can use rest api Pull Requests - Get Pull Request with includeWorkItemRefs=true:

If you would like to get all pull requests and associated work items, you have to do with 2 steps:
# Define your organization, project, repository, and PAT
$organization = "your-organization"
$project = "your-project"
$repository = "your-repository"
$PAT = "your-PAT"
# Create the base64 encoded authorization header
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "",$PAT)))
# Define the API URL for pull requests
$apiUrl = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/pullrequests?api-version=6.0"
# Call the API to get all pull requests
$response = Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
# Loop through each pull request
foreach($pullRequest in $response.value) {
# Get the pull request ID
$pullRequestId = $pullRequest.pullRequestId
# Define the API URL for work items associated with the pull request
$workItemsApiUrl = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repository/pullrequests/$pullRequestId/workitems?api-version=6.0"
# Call the API to get associated work items
$workItemsResponse = Invoke-RestMethod -Uri $workItemsApiUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
# Print the pull request ID and associated work item IDs
Write-Host "Pull Request ID: $pullRequestId"
Write-Host "Associated Work Items:"
foreach($workItem in $workItemsResponse.value) {
Write-Host $workItem.id
}
}

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With