REST API 入门

Azure DevOps Services | Azure DevOps Server 2022 - Azure DevOps Server 2019

使用本文提供的 REST API 将应用与 Azure DevOps 集成。

API 遵循常见模式,如以下示例所示。

VERB https://{instance}/{collection}/{team-project}/_apis/{area}/{resource}?api-version={version}

提示

随着 API 的发展,我们建议在每个请求中包含 API 版本。 这种做法有助于避免 API 中可能会中断的意外更改。

Azure DevOps Services

对于 Azure DevOps Services, instance 模式 dev.azure.com/{organization}collectionDefaultCollection如下所示。

VERB https://dev.azure.com/{organization}/_apis/{area}/{resource}?api-version={version}

以下示例演示如何获取组织中的项目列表。

curl -u {username}:{personalaccesstoken} https://dev.azure.com/{organization}/_apis/projects?api-version=2.0

如果要通过 HTTP 标头提供个人访问令牌(PAT),必须先将其转换为 Base64 字符串。 以下示例演示如何使用 C# 转换为 Base64。 然后,可以采用 HTTP 标头格式提供生成的字符串。

Authorization: Basic BASE64PATSTRING

以下示例演示了使用 HttpClient 类C# 。

public static async void GetProjects()
{
	try
	{
		var personalaccesstoken = "PAT_FROM_WEBSITE";

		using (HttpClient client = new HttpClient())
		{
			client.DefaultRequestHeaders.Accept.Add(
				new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

			client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
				Convert.ToBase64String(
					System.Text.ASCIIEncoding.ASCII.GetBytes(
						string.Format("{0}:{1}", "", personalaccesstoken))));

			using (HttpResponseMessage response = client.GetAsync(
						"https://dev.azure.com/{organization}/_apis/projects").Result)
			{
				response.EnsureSuccessStatusCode();
				string responseBody = await response.Content.ReadAsStringAsync();
				Console.WriteLine(responseBody);
			}
		}
	}
	catch (Exception ex)
	{
		Console.WriteLine(ex.ToString());
	}
}

我们的大多数示例都使用 PAT,因为它们是使用服务进行身份验证的紧凑示例。 但是,Azure DevOps Services 提供了各种身份验证机制,包括 Microsoft 身份验证库(MSAL)、OAuth 和会话令牌。 有关详细信息,请参阅 身份验证指南,帮助你确定最适合你的方案。

Azure DevOps Server

对于 Azure DevOps Server, instance{server:port}. 非 SSL 连接的默认端口为 8080。

默认集合是 DefaultCollection,但可以使用任何集合。

下面介绍如何使用跨 SSL 的默认端口和集合从 Azure DevOps Server 获取项目列表:

curl -u {username}:{personalaccesstoken} https://{server}/DefaultCollection/_apis/projects?api-version=2.0

若要跨非 SSL 连接获取相同的列表,

curl -u {username}:{personalaccesstoken} http://{server}:8080/DefaultCollection/_apis/projects?api-version=2.0

这些示例使用 PAT,这要求你 创建 PAT

响应

应收到如下所示的响应。

{
    "value": [
        {
            "id": "eb6e4656-77fc-42a1-9181-4c6d8e9da5d1",
            "name": "Fabrikam-Fiber-TFVC",
            "url": "https: //dev.azure.com/fabrikam-fiber-inc/_apis/projects/eb6e4656-77fc-42a1-9181-4c6d8e9da5d1",
            "description": "TeamFoundationVersionControlprojects",
            "collection": {
                "id": "d81542e4-cdfa-4333-b082-1ae2d6c3ad16",
                "name": "DefaultCollection",
                "url": "https: //dev.azure.com/fabrikam-fiber-inc/_apis/projectCollections/d81542e4-cdfa-4333-b082-1ae2d6c3ad16",
                "collectionUrl": "https: //dev.azure.com/fabrikam-fiber-inc"
            },
            "defaultTeam": {
                "id": "66df9be7-3586-467b-9c5f-425b29afedfd",
                "name": "Fabrikam-Fiber-TFVCTeam",
                "url": "https: //dev.azure.com/fabrikam-fiber-inc/_apis/projects/eb6e4656-77fc-42a1-9181-4c6d8e9da5d1/teams/66df9be7-3586-467b-9c5f-425b29afedfd"
            }
        },
        {
            "id": "6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c",
            "name": "Fabrikam-Fiber-Git",
            "url": "https: //dev.azure.com/fabrikam-fiber-inc/_apis/projects/6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c",
            "description": "Gitprojects",
            "collection": {
                "id": "d81542e4-cdfa-4333-b082-1ae2d6c3ad16",
                "name": "DefaultCollection",
                "url": "https: //dev.azure.com/fabrikam-fiber-inc/_apis/projectCollections/d81542e4-cdfa-4333-b082-1ae2d6c3ad16",
                "collectionUrl": "https: //dev.azure.com/fabrikam-fiber-inc"
            },
            "defaultTeam": {
                "id": "8bd35c5e-30bb-4834-a0c4-d576ce1b8df7",
                "name": "Fabrikam-Fiber-GitTeam",
                "url": "https: //dev.azure.com/fabrikam-fiber-inc/_apis/projects/6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c/teams/8bd35c5e-30bb-4834-a0c4-d576ce1b8df7"
            }
        }
    ],
    "count": 2
}

响应是 JSON,通常是从 REST API 返回的内容,尽管存在一些例外情况,例如 Git Blob

现在,可以查看特定的 API 区域 ,例如 工作项跟踪Git ,并获取所需的资源。 继续阅读,详细了解这些 API 中使用的常规模式。

HTTP 谓词

谓词 用于...
GET 获取资源或资源列表
POST 创建资源,使用更高级查询获取资源列表
PUT 如果资源不存在,则创建资源,或者,如果不存在,请更新它
修补程序 更新资源
DELETE 删除资源

请求标头和请求内容

提供请求正文(通常使用 POST、PUT 和 PATCH 谓词),包括描述正文的请求标头。 例如,

POST https://dev.azure.com/fabrikam-fiber-inc/_apis/build-release/requests
Content-Type: application/json
{
   "definition": {
      "id": 3
   },
   "reason": "Manual",
   "priority": "Normal"
}

HTTP 方法重写

某些 Web 代理可能仅支持 HTTP 谓词 GET 和 POST,但不支持更现代的 HTTP 谓词,如 PATCH 和 DELETE。 如果调用可能通过其中一个代理,则可以使用 POST 方法发送实际谓词,并使用标头替代该方法。 例如,你可能想要 更新工作项PATCH _apis/wit/workitems/3),但可能需要通过仅允许 GET 或 POST 的代理。 可以将正确的谓词(在本例中修补)作为 HTTP 请求标头参数传递,并使用 POST 作为实际的 HTTP 方法。

POST https://dev.azure.com/fabrikam-fiber-inc/_apis/wit/workitems/3
X-HTTP-Method-Override: PATCH
{
   (PATCH request body)
}

响应代码

响应 说明
200 成功,并且有一个响应正文。
201 成功,在创建资源时。 成功创建资源时,某些 API 返回 200。 查看用于确保使用的 API 的文档。
204 成功,没有响应正文。 例如,删除资源时会收到此响应。
400 URL 或请求正文中的参数无效。
401 身份验证失败。 通常,此响应是由于缺少或格式不正确的授权标头。
403 经过身份验证的用户无权执行该操作。
404 资源不存在,或者经过身份验证的用户无权查看该资源是否存在。
409 请求与服务器上的数据状态之间存在冲突。 例如,如果尝试提交拉取请求并且已存在提交拉取请求,则响应代码为 409。

跨域资源共享 (CORS)

Azure DevOps Services 支持 CORS,它使 JavaScript 代码能够从域提供,而不是 dev.azure.com/* 向 Azure DevOps Services REST API 发出 Ajax 请求。 每个请求都必须提供凭据(PAT 和 OAuth 访问令牌都是受支持的选项)。 示例:

    $( document ).ready(function() {
        $.ajax({
            url: 'https://dev.azure.com/fabrikam/_apis/projects?api-version=1.0',
            dataType: 'json',
            headers: {
                'Authorization': 'Basic ' + btoa("" + ":" + myPatToken)
            }
        }).done(function( results ) {
            console.log( results.value[0].id + " " + results.value[0].name );
        });
    });

(替换为 myPatToken 个人访问令牌)

版本控制

Azure DevOps REST API 经过版本控制,以确保应用程序和服务继续随着 API 的发展而工作。

准则

  • 使用每个请求指定 API 版本(必需)。
  • 设置 API 版本的格式,如下所示: {major}。{minor}-{stage}。{resource-version}。 例如,1.01.11.2-preview2.0
  • 使用以下版本格式指定 API 在预览版时的特定修订: 1.0-preview.11.0-preview.2 (1.0(例如) )发布 API 后,其预览版本 (1.0 预览版) 已弃用,可在 12 周后停用。
  • 升级到 API 的已发布版本。 停用预览 API 后,指定 -preview 版本的请求将被拒绝。

使用情况

在 HTTP 请求的标头中指定 API 版本,或指定为 URL 查询参数。

HTTP 请求标头:

Accept: application/json;api-version=1.0

查询参数:

GET https://dev.azure.com/{organization}/_apis/{area}/{resource}?api-version=1.0

支持的版本

有关支持的版本的信息,请参阅 REST API 版本控制、支持的版本