You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Azure DevOps Server API获取全部历史Pull Requests列表?

获取Azure DevOps项目所有历史Pull Requests的解决方案

你当前的代码调用Azure DevOps API时,默认只返回活跃状态的Pull Requests(比如Open、Draft),要获取所有历史创建的PR(包括已完成、已关闭的),需要调整API请求参数并处理分页。

核心修改点

  1. 添加status=all参数:在API请求URL中加入该参数,指定返回所有状态的PR
  2. 处理分页逻辑:Azure DevOps API默认单次最多返回100条数据,若PR总数超过这个值,需通过continuationToken循环请求直到获取全部数据

修改后的完整代码

import os
import base64
import requests
import csv

# 配置变量
org_url = "https://organization.com/collection"
project_name = "project"
PAT = os.environ.get('AzureDevOpsPAT')

# 设置请求头
headers = {}
if PAT is not None:
    headers['Authorization'] = 'Basic ' + base64.b64encode(bytes(':' + PAT, 'utf-8')).decode('ascii')
    headers['Content-Type'] = 'application/json'
    headers['Accept'] = 'application/json'

all_pull_requests = []
continuation_token = None

# 循环获取所有分页的PR数据
while True:
    # 构建请求URL,包含状态参数和分页token
    url = f"{org_url}/{project_name}/_apis/git/pullrequests?status=all&$top=100"
    if continuation_token:
        url += f"&continuationToken={continuation_token}"
    
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    pr_page = response.json()
    
    all_pull_requests.extend(pr_page["value"])
    
    # 检查是否还有下一页
    continuation_token = pr_page.get("continuationToken")
    if not continuation_token:
        break

# 写入CSV文件
with open('all_pull_requests.csv', mode='w', newline='', encoding='utf-8') as csv_file:
    fieldnames = ['PullRequestId', 'Title', 'Status', 'CreatedDate', 'CreatedBy', 'RepositoryName']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()
    for pr in all_pull_requests:
        writer.writerow({
            'PullRequestId': pr['pullRequestId'],
            'Title': pr['title'],
            'Status': pr['status'],
            'CreatedDate': pr['creationDate'],
            'CreatedBy': pr['createdBy']['displayName'],
            'RepositoryName': pr['repository']['name']  # 新增仓库名称字段
        })

后续需求扩展方向

  • 所属仓库:PR数据的repository字段已包含仓库名称、ID等信息,代码中已添加RepositoryName字段
  • 关联工作项:每个PR的workItemRefs字段存储关联的工作项ID,可通过Azure DevOps的Work Items API获取详情
  • 区域路径:从工作项详情的fields['System.AreaPath']字段中提取对应值

内容的提问来源于stack exchange,提问作者cristopheridlc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 13:17:39