如何使用Azure DevOps API(Python)为Pull Request添加评论
在Python中通过Azure DevOps API为Pull Request添加评论的方法
前置准备
- 生成Azure DevOps个人访问令牌(PAT),需包含**Code (Read & Write)**权限,确保能操作PR评论。
- 确认以下信息:组织名、项目名、目标仓库ID、要评论的PR编号。
实现步骤与代码示例
导入依赖库
使用requests库发送HTTP请求,base64处理认证编码:import base64 import requests配置认证与请求头
Azure DevOps API采用Basic认证,将PAT编码后放入请求头:# 替换为你的实际参数 organization = "your-org-name" project = "your-project-name" repo_id = "your-repo-guid" pr_number = "123" # 你的PR编号 pat = "your-personal-access-token" # 构造认证头 credentials = f":{pat}" encoded_credentials = base64.b64encode(credentials.encode()).decode() headers = { "Authorization": f"Basic {encoded_credentials}", "Content-Type": "application/json" }构造评论请求体
根据评论场景选择不同的请求体:- 全局评论(不关联具体文件行):
payload = { "comments": [ { "parentCommentId": 0, "content": "这是通过API添加的全局PR评论", "commentType": "text" } ], "status": "active", "threadContext": { "filePath": "/", "leftFileStart": None, "leftFileEnd": None, "rightFileStart": None, "rightFileEnd": None } } - 针对特定文件行的评论:
payload = { "comments": [ { "parentCommentId": 0, "content": "这里的逻辑需要再梳理下", "commentType": "text" } ], "status": "active", "threadContext": { "filePath": "/src/utils.py", # 目标文件路径 "rightFileStart": 45, # 新代码的起始行号 "rightFileEnd": 45 # 新代码的结束行号(单行则与起始行一致) } }
- 全局评论(不关联具体文件行):
发送请求并处理响应
调用API创建评论线程:api_url = f"https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repo_id}/pullRequests/{pr_number}/threads?api-version=7.1-preview.1" response = requests.post(api_url, headers=headers, json=payload) if response.status_code == 201: print("评论添加成功") else: print(f"添加失败:状态码 {response.status_code},错误信息:{response.text}")
额外说明
- 如果需要回复现有评论线程,需先获取目标线程ID,然后调用
POST /_apis/git/repositories/{repo_id}/pullRequests/{pr_number}/threads/{thread_id}/comments?api-version=7.1-preview.1,请求体只需传入content和commentType。 - 仓库ID可通过API获取:发送
GET https://dev.azure.com/{org}/{proj}/_apis/git/repositories?api-version=7.1-preview.1,返回结果中包含各仓库的id字段。 - 确保使用兼容的API版本,示例中使用的
7.1-preview.1是当前稳定可用的版本。
内容的提问来源于stack exchange,提问作者anjalib
相关产品推荐
相关产品推荐

