如何通过Python调用ADO REST API获取整个项目的工作项ID?
解决方案:获取Azure DevOps项目全量工作项ID并批量拉取数据
一、获取整个项目的所有工作项ID(跨100+团队)
要覆盖项目内所有团队的工作项,直接用Wiql查询API是最高效的方式,无需逐个团队拉取。
核心思路
构造Wiql查询语句,指定查询当前项目下的所有工作项ID,然后处理API的分页返回,将所有ID收集到列表中。
实现步骤&代码示例
- 构造Wiql查询:仅查询
System.Id字段,减少数据传输量 - 循环处理分页结果:ADO Wiql API默认每页返回200条,通过
continuationtoken参数获取后续页面的数据
import requests from requests.auth import HTTPBasicAuth import time # 配置信息 ORG_URL = "https://dev.azure.com/your-org" PROJECT_NAME = "your-project" PAT = "your-pat-token" # 需具备工作项读取权限 def get_all_workitem_ids(): ids = [] continuation_token = None headers = {"Content-Type": "application/json"} auth = HTTPBasicAuth("", PAT) while True: # 构造请求体 wiql_query = { "query": f"SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = '{PROJECT_NAME}'" } url = f"{ORG_URL}/{PROJECT_NAME}/_apis/wit/wiql?api-version=7.1-preview.2" # 如果有续传令牌,添加到请求参数 if continuation_token: url += f"&continuationtoken={continuation_token}" response = requests.post(url, json=wiql_query, headers=headers, auth=auth) response.raise_for_status() data = response.json() # 提取当前页的工作项ID ids.extend([item["id"] for item in data["workItems"]]) # 检查是否还有下一页 continuation_token = data.get("continuationToken") if not continuation_token: break # 加个小延迟,避免触发速率限制 time.sleep(0.5) return ids
二、分批次拉取工作项数据(每次200个ID)
拿到全量ID列表后,按每200个ID一组拆分,调用Work Items - List API批量获取数据,同时解决长字段截断问题。
关键注意点
- 明确指定需要的字段(或用
$expand=All),确保长文本字段(比如描述、评论)完整返回,不会被截断 - 处理API速率限制,必要时添加重试机制
实现步骤&代码示例
def batch_fetch_workitems(workitem_ids, batch_size=200): all_workitems = [] headers = {"Content-Type": "application/json"} auth = HTTPBasicAuth("", PAT) # 拆分ID列表为批量 for i in range(0, len(workitem_ids), batch_size): batch_ids = workitem_ids[i:i+batch_size] # 把ID转为逗号分隔的字符串 ids_str = ",".join(map(str, batch_ids)) # 请求API,指定需要的字段(这里用$expand=All获取所有字段,也可以自定义fields参数) url = f"{ORG_URL}/{PROJECT_NAME}/_apis/wit/workitems?ids={ids_str}&$expand=All&api-version=7.1-preview.3" response = requests.get(url, headers=headers, auth=auth) response.raise_for_status() workitems = response.json()["value"] all_workitems.extend(workitems) # 延迟避免限流 time.sleep(1) return all_workitems # 存储数据到文件(以JSON为例,也可以导出为CSV适配报表工具) def save_workitems_to_file(workitems, filename="ado_workitems.json"): import json with open(filename, "w", encoding="utf-8") as f: json.dump(workitems, f, indent=2, ensure_ascii=False) # 主流程 if __name__ == "__main__": print("开始获取所有工作项ID...") all_ids = get_all_workitem_ids() print(f"共获取到 {len(all_ids)} 个工作项ID") print("开始批量拉取工作项数据...") all_workitems = batch_fetch_workitems(all_ids) print("开始保存数据...") save_workitems_to_file(all_workitems) print("数据保存完成!")
额外提示
- PAT权限:确保你的PAT拥有
Work Items (Read)权限,否则会返回403错误 - 速率限制:ADO API的速率限制是每分钟300次请求,上述代码的延迟已经足够应对大部分场景,如果遇到429错误,可以增加延迟时间或添加重试逻辑
- 字段自定义:如果不需要所有字段,可以把
$expand=All替换为fields=System.Id,System.Title,System.Description,...,指定你需要的字段,提升请求效率
内容的提问来源于stack exchange,提问作者m00nface
相关产品推荐
相关产品推荐

