開始使用 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是且 collectionDefaultCollectiondev.azure.com/{organization} ,因此模式看起來像下列範例。

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 Proxy 可能只支援 HTTP 動詞 GET 和 POST,但不支援更現代化的 HTTP 動詞,例如 PATCH 和 DELETE。 如果您的呼叫可能通過其中一個 Proxy,您可以使用 POST 方法傳送實際的動詞,並搭配標頭來覆寫 方法。 例如,您可能想要 更新工作專案PATCH _apis/wit/workitems/3),但您可能必須經過只允許 GET 或 POST 的 Proxy。 您可以傳遞適當的動詞命令(在此案例中為 PATCH)作為 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。 在發行 API 後 (以 1.0 為例),其預覽版本 (1.0-preview) 將被取代並可在 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 版本控制、支援的版本