使用Azure DevOps API获取与Git标签关联的Commit ID
通过Azure DevOps API根据Git标签获取关联的Commit ID
1. 确定API端点
使用Azure DevOps Git refs API筛选指定标签,端点格式如下:
GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/refs?filter=tags/{tagName}&api-version=7.1-preview.1
参数说明:
{organization}:你的Azure DevOps组织名称{project}:目标项目名称{repositoryId}:Git仓库的ID或名称{tagName}:要查询的Git标签名称(无需加refs/tags/前缀,API会自动处理)
2. 认证方式
需使用**个人访问令牌(PAT)**完成认证,令牌需授予Code (Read)权限。将PAT进行Base64编码(编码内容为:{PAT},注意前缀的冒号),放在请求头的Authorization字段中,格式为Basic {base64编码后的内容}。
3. 示例请求
curl示例
curl -H "Authorization: Basic {base64编码的PAT}" \ "https://dev.azure.com/my-org/my-project/_apis/git/repositories/my-repo/refs?filter=tags/v1.0.0&api-version=7.1-preview.1"
Python示例
import requests import base64 # 配置参数 organization = "my-org" project = "my-project" repo_id = "my-repo" tag_name = "v1.0.0" pat = "your-pat-token" # 处理认证 auth = base64.b64encode(f":{pat}".encode()).decode() headers = {"Authorization": f"Basic {auth}"} # 构建请求URL url = f"https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repo_id}/refs?filter=tags/{tag_name}&api-version=7.1-preview.1" # 发送请求 response = requests.get(url, headers=headers) response.raise_for_status() data = response.json()
4. 提取Commit ID
API返回的JSON数据中,value数组包含匹配的标签信息,需根据标签类型提取Commit ID:
- 轻量标签:直接取
value[0].objectId - 附注标签:取
value[0].object.objectId(附注标签本身是独立对象,其指向的目标才是Commit)
示例解析代码(Python):
if data["value"]: tag_ref = data["value"][0] # 判断是否为附注标签 if tag_ref["object"]["objectType"] == "tag": commit_id = tag_ref["object"]["objectId"] else: commit_id = tag_ref["objectId"] print(f"关联的Commit ID: {commit_id}") else: print("未找到指定标签")
内容的提问来源于stack exchange,提问作者user989988
相关产品推荐
相关产品推荐

