如何通过Python脚本调用Azure API获取指定仓库(如XYZ)的Repository ID
只获取指定Azure仓库ID的Python实现方案
没问题,我来帮你调整脚本,轻松抓取指定仓库(比如XYZ)的ID,这样就不会生成超大的输出文件啦!下面给你两种常用的实现方式,选你顺手的来:
方式一:使用官方Azure DevOps Python库(推荐)
官方库封装了API调用,代码更简洁易维护。
首先确保安装依赖:
pip install azure-devops
修改后的脚本示例:
from azure.devops.connection import Connection from msrest.authentication import BasicAuthentication # 替换成你的配置信息 ORGANIZATION_URL = "https://dev.azure.com/你的组织名" PERSONAL_ACCESS_TOKEN = "你的PAT令牌" TARGET_REPO_NAME = "XYZ" # 要查找的仓库名称 PROJECT_NAME = "你的项目名" # 如果仓库属于特定项目,填这里;组织级仓库可以注释掉 # 建立连接 credentials = BasicAuthentication('', PERSONAL_ACCESS_TOKEN) connection = Connection(base_url=ORGANIZATION_URL, creds=credentials) # 获取Git客户端 git_client = connection.clients.get_git_client() try: # 直接通过API筛选指定名称的仓库,减少返回数据量 repo_search_params = {"name": TARGET_REPO_NAME} # 如果是项目级仓库,传入project参数;组织级的话去掉这个参数 repos = git_client.get_repositories(project=PROJECT_NAME, search_criteria=repo_search_params) if repos: # 仓库名称唯一,直接取第一个结果的ID target_repo_id = repos[0].id print(f"✅ 仓库 {TARGET_REPO_NAME} 的ID是: {target_repo_id}") # 可选:保存到文件 with open("target_repo_id.txt", "w") as f: f.write(target_repo_id) print("📝 ID已保存到target_repo_id.txt") else: print(f"❌ 未找到名称为 {TARGET_REPO_NAME} 的仓库,请检查名称是否正确(大小写敏感)") except Exception as e: print(f"⚠️ 请求出错: {str(e)}")
方式二:直接用Requests调用API
如果不想用官方库,直接发HTTP请求也可以:
import requests import base64 # 替换成你的配置信息 ORGANIZATION = "你的组织名" PROJECT = "你的项目名" # 项目级仓库必填,组织级去掉 PAT = "你的PAT令牌" TARGET_REPO_NAME = "XYZ" # 构造API请求URL,带筛选参数 if PROJECT: url = f"https://dev.azure.com/{ORGANIZATION}/{PROJECT}/_apis/git/repositories?api-version=7.1-preview.1&searchCriteria.name={TARGET_REPO_NAME}" else: url = f"https://dev.azure.com/{ORGANIZATION}/_apis/git/repositories?api-version=7.1-preview.1&searchCriteria.name={TARGET_REPO_NAME}" # 构造认证头 headers = { "Authorization": f"Basic {base64.b64encode(f':{PAT}'.encode()).decode()}" } try: response = requests.get(url, headers=headers) response.raise_for_status() # 检查请求是否成功 repos = response.json()["value"] if repos: target_repo_id = repos[0]["id"] print(f"✅ 仓库 {TARGET_REPO_NAME} 的ID是: {target_repo_id}") with open("target_repo_id.txt", "w") as f: f.write(target_repo_id) print("📝 ID已保存到target_repo_id.txt") else: print(f"❌ 未找到名称为 {TARGET_REPO_NAME} 的仓库,请检查名称是否正确(大小写敏感)") except requests.exceptions.RequestException as e: print(f"⚠️ 请求出错: {str(e)}")
几个关键注意点
- 权限问题:确保你的PAT拥有Git仓库的读取权限,否则会返回403错误
- 大小写敏感:Azure仓库名称是区分大小写的,要和平台上显示的完全一致
- 重名处理:如果你的组织/项目里有重名仓库(不推荐),可以添加更多筛选条件,比如
search_criteria.projectName来缩小范围 - API版本:示例用的是
7.1-preview.1,可以根据需要换成最新的稳定版本
内容的提问来源于stack exchange,提问作者Aditya
相关产品推荐
相关产品推荐

