Haven't been able to find a direct method for this anywhere. How can I add comments to a pull request via Azure Devops API in Python?
We have the sample API to create a new thread with a comment for a pull request.
We can also call another API in this sample to add a new comment in an existing thread of a pull request.
Here is my python script for your reference.
import base64
import json
import requests
# Define your Azure DevOps organization, project, repo, pull request id and personal access token
organization = "YourADOOrgName"
project = "TheProjectName"
repository_name = "RepoName"
pull_request_id = 108
personal_access_token = 'xxxxxx'
# Encode the personal access token in base64
base64_pat = base64.b64encode(f':{personal_access_token}'.encode('utf-8')).decode('utf-8')
headers = {
"Authorization": f"Basic {base64_pat}",
"Content-Type": "application/json"
}
# Define the URL for a new thread of the PR
thread_url = f"https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repository_name}/pullRequests/{pull_request_id}/threads?api-version=7.1-preview.1"
thread_body = {
"comments": [
{
"parentCommentId": 0,
"content": "Test comment 1 by Python in another thread",
"commentType": 1
}
],
"status": "active"
}
# Make the API request to create a thread with comment
thread_response = requests.post(thread_url, headers=headers, json=thread_body).json()
# Print the response of the new thread and the id
print(json.dumps(thread_response, indent=4))
thread_id = thread_response.get('id')
print(f"The new thread id is {thread_id}")
# Define the URL for a comment in an exsiting thread
thread_comment_url = f"https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repository_name}/pullRequests/{pull_request_id}/threads/{thread_id}/comments?api-version=7.1-preview.1"
thread_comment_body = {
"content": "Test comment 2 by Python in another thread",
"parentCommentId": 1,
"commentType": 1
}
# Make the API request to create a comment in the exsiting thread
thread_comment_response = requests.post(thread_comment_url, headers=headers, json=thread_comment_body).json()
# Print the response of the new comment
print(json.dumps(thread_comment_response, indent=4))
Per the follow-up query to set the thread status, we can call this API to update the status
value as one of those in the CommentThreadsStatus.
# Generate URL to update thread status
update_thread_url = f"https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repository_name}/pullRequests/{pull_request_id}/threads/{thread_id}?api-version=7.1-preview.1"
update_thread_body = {
"status": "fixed"
}
# Make the API request to update thread status
update_thread_response = requests.patch(update_thread_url, headers=headers, json=update_thread_body).json()
# Print the response of the updated thread
print(json.dumps(update_thread_response, indent=4))