Azure DevOps サービス |Azure DevOps Server |Azure DevOps Server 2022
この記事では、Azure DevOps Services の実用的な REST API の例を示します。 これらのサンプルは、プロジェクトの取得、作業項目の管理、Microsoft Entra IDでのセキュリティで保護された認証パターンの使用などの一般的な操作を示しています。
Von Bedeutung
より安全なMicrosoft Entraトークンを、リスクの高い個人アクセス トークンよりも使用することを検討してください。 詳細については、「 PAT 使用量の削減」を参照してください。 認証ガイダンスを確認して、ニーズに適した認証メカニズムを選択します。
認証の概要
Azure DevOps REST API では、いくつかの認証方法がサポートされています。
- Microsoft Entra ID - 運用環境のアプリケーションに推奨 (これらのサンプルで使用)
- 個人用アクセス トークン (AT) - スクリプトとテストのための簡単な認証
- OAuth 2.0 - サード パーティ製アプリケーションの場合
- サービス プリンシパル - 自動化されたシナリオ用
ヒント
この記事の後半でAIを使用してこのタスクを支援することができます。また、作業を開始するには、Azure DevOps MCP ServerでAIサポートを有効にする方法を参照してください。
Microsoft Entra ID認証
Microsoft Entra ID認証の場合は、アプリケーションを登録し、アクセス トークンを取得する必要があります。 Microsoft Authentication Library (MSAL) を使用して認証する方法を次に示します。
まず、必要な NuGet パッケージをインストールします。
<PackageReference Include="Microsoft.Identity.Client" Version="4.67.2" />
using Microsoft.Identity.Client;
using System.Net.Http.Headers;
public async Task<string> GetAccessTokenAsync()
{
var app = PublicClientApplicationBuilder
.Create("{your-client-id}")
.WithAuthority("https://login.microsoftonline.com/{your-tenant-id}")
.WithRedirectUri("http://localhost")
.Build();
var scopes = new[] { "https://app.vssps.visualstudio.com/.default" };
try
{
var result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
return result.AccessToken;
}
catch (MsalException ex)
{
Console.WriteLine($"Authentication failed: {ex.Message}");
throw;
}
}
REST API のサンプル
プロジェクトの一覧表示 (GET)
組織内のすべてのプロジェクトを取得します。
C# の例
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
public async Task<string> GetProjectsAsync(string organization)
{
using var client = new HttpClient();
// Get Microsoft Entra ID access token
var entraIdAccessToken = await GetAccessTokenAsync();
// Set base address and headers
client.BaseAddress = new Uri($"https://dev.azure.com/{organization}/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Add authentication header
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", entraIdAccessToken);
try
{
var response = await client.GetAsync("_apis/projects?api-version=7.2");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Request failed: {ex.Message}");
throw;
}
}
PowerShell の例
# Install the Az.Accounts module if not already installed
# Install-Module -Name Az.Accounts -Force
# Sign in (interactive prompt) or use Connect-AzAccount -Identity for managed identity
Connect-AzAccount -TenantId "your-tenant-id"
$organization = "your-organization"
# Get access token for Azure DevOps
$token = Get-AzAccessToken -ResourceUrl "https://app.vssps.visualstudio.com/"
$headers = @{
'Authorization' = "Bearer $($token.Token)"
'Accept' = 'application/json'
}
$uri = "https://dev.azure.com/$organization/_apis/projects?api-version=7.2"
try {
$response = Invoke-RestMethod -Uri $uri -Method Get -Headers $headers
Write-Host "Retrieved $($response.count) projects"
$response.value | ForEach-Object { Write-Host "- $($_.name)" }
}
catch {
Write-Error "Failed to retrieve projects: $($_.Exception.Message)"
}
作業項目の作成 (POST)
プロジェクトに新しい作業項目を作成します。
C# の例
using System.Text;
using Newtonsoft.Json;
public async Task<string> CreateWorkItemAsync(string organization, string project)
{
using var client = new HttpClient();
// Get Microsoft Entra ID access token
var entraIdAccessToken = await GetAccessTokenAsync();
// Set base address and headers
client.BaseAddress = new Uri($"https://dev.azure.com/{organization}/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", entraIdAccessToken);
var patchOperations = new[]
{
new { op = "add", path = "/fields/System.Title", value = "Sample work item" },
new { op = "add", path = "/fields/System.Description", value = "Created via REST API with Microsoft Entra ID" },
new { op = "add", path = "/fields/System.Tags", value = "api; sample; entra-id" }
};
var json = JsonConvert.SerializeObject(patchOperations);
var content = new StringContent(json, Encoding.UTF8, "application/json-patch+json");
try
{
var response = await client.PostAsync($"{project}/_apis/wit/workitems/$Task?api-version=7.2", content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Request failed: {ex.Message}");
throw;
}
}
PowerShell の例
# Sign in (interactive prompt) or use Connect-AzAccount -Identity for managed identity
Connect-AzAccount -TenantId "your-tenant-id"
$organization = "your-organization"
$project = "your-project"
# Get access token for Azure DevOps
$token = Get-AzAccessToken -ResourceUrl "https://app.vssps.visualstudio.com/"
$headers = @{
'Authorization' = "Bearer $($token.Token)"
'Content-Type' = 'application/json-patch+json'
}
$body = @(
@{
op = "add"
path = "/fields/System.Title"
value = "Sample work item"
},
@{
op = "add"
path = "/fields/System.Description"
value = "Created via REST API with Microsoft Entra ID"
},
@{
op = "add"
path = "/fields/System.Tags"
value = "api; sample; entra-id"
}
) | ConvertTo-Json
$uri = "https://dev.azure.com/$organization/$project/_apis/wit/workitems/`$Task?api-version=7.2"
try {
$response = Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Body $body
Write-Host "Work item created with ID: $($response.id)"
}
catch {
Write-Error "Failed to create work item: $($_.Exception.Message)"
}
作業項目の更新 (PATCH)
既存の作業項目の状態を更新します。
C# の例
using System.Text;
using Newtonsoft.Json;
public async Task<string> UpdateWorkItemAsync(string organization, string project, int workItemId)
{
using var client = new HttpClient();
// Get Microsoft Entra ID access token
var entraIdAccessToken = await GetAccessTokenAsync();
// Set base address and headers
client.BaseAddress = new Uri($"https://dev.azure.com/{organization}/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", entraIdAccessToken);
var patchOperations = new[]
{
new
{
op = "add",
path = "/fields/System.State",
value = "In Progress"
},
new
{
op = "add",
path = "/fields/System.AssignedTo",
value = "user@example.com"
}
};
var json = JsonConvert.SerializeObject(patchOperations);
var content = new StringContent(json, Encoding.UTF8, "application/json-patch+json");
try
{
var response = await client.PatchAsync($"{project}/_apis/wit/workitems/{workItemId}?api-version=7.2", content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Request failed: {ex.Message}");
throw;
}
}
PowerShell の例
# Sign in (interactive prompt) or use Connect-AzAccount -Identity for managed identity
Connect-AzAccount -TenantId "your-tenant-id"
$organization = "your-organization"
$project = "your-project"
$workItemId = 123 # Replace with actual work item ID
# Get access token for Azure DevOps
$token = Get-AzAccessToken -ResourceUrl "https://app.vssps.visualstudio.com/"
$headers = @{
'Authorization' = "Bearer $($token.Token)"
'Content-Type' = 'application/json-patch+json'
}
$body = @(
@{
op = "add"
path = "/fields/System.State"
value = "In Progress"
},
@{
op = "add"
path = "/fields/System.AssignedTo"
value = "user@example.com"
}
) | ConvertTo-Json
$uri = "https://dev.azure.com/$organization/$project/_apis/wit/workitems/$workItemId?api-version=7.2"
try {
$response = Invoke-RestMethod -Uri $uri -Method Patch -Headers $headers -Body $body
Write-Host "Work item $workItemId updated successfully"
}
catch {
Write-Error "Failed to update work item: $($_.Exception.Message)"
}
作業項目の削除 (DELETE)
プロジェクトから作業項目を削除します。
C# の例
public async Task<bool> DeleteWorkItemAsync(string organization, string project, int workItemId)
{
using var client = new HttpClient();
// Get Microsoft Entra ID access token
var entraIdAccessToken = await GetAccessTokenAsync();
// Set base address and headers
client.BaseAddress = new Uri($"https://dev.azure.com/{organization}/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", entraIdAccessToken);
try
{
var response = await client.DeleteAsync($"{project}/_apis/wit/workitems/{workItemId}?api-version=7.2");
response.EnsureSuccessStatusCode();
Console.WriteLine($"Work item {workItemId} deleted successfully");
return true;
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Request failed: {ex.Message}");
throw;
}
}
.NET クライアント ライブラリ
.NET アプリケーションの場合は、Azure DevOps .NET クライアント ライブラリを使用して、型の安全性を向上させ、開発を容易にします。
取り付け
次の NuGet パッケージをプロジェクトに追加します。
<PackageReference Include="Microsoft.TeamFoundationServer.Client" Version="19.232.1" />
<PackageReference Include="Microsoft.VisualStudio.Services.Client" Version="19.232.1" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.67.2" />
.NET クライアントを使用してプロジェクトを取得する
using Microsoft.TeamFoundation.Core.WebApi;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.WebApi;
using Microsoft.Identity.Client;
public async Task<IEnumerable<TeamProjectReference>> GetProjectsAsync(string organizationUrl)
{
var uri = new Uri(organizationUrl);
// Get Microsoft Entra ID access token
var entraIdAccessToken = await GetAccessTokenAsync();
var credentials = new VssOAuthAccessTokenCredential(entraIdAccessToken);
using var connection = new VssConnection(uri, credentials);
using var projectClient = connection.GetClient<ProjectHttpClient>();
try
{
var projects = await projectClient.GetProjects();
return projects;
}
catch (Exception ex)
{
Console.WriteLine($"Error retrieving projects: {ex.Message}");
throw;
}
}
.NET クライアントを使用して作業項目を作成する
using Microsoft.TeamFoundation.WorkItemTracking.WebApi;
using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models;
using Microsoft.VisualStudio.Services.WebApi.Patch;
using Microsoft.VisualStudio.Services.WebApi.Patch.Json;
using Microsoft.Identity.Client;
public async Task<WorkItem> CreateWorkItemAsync(string organizationUrl, string project)
{
var uri = new Uri(organizationUrl);
// Get Microsoft Entra ID access token
var entraIdAccessToken = await GetAccessTokenAsync();
var credentials = new VssOAuthAccessTokenCredential(entraIdAccessToken);
using var connection = new VssConnection(uri, credentials);
using var witClient = connection.GetClient<WorkItemTrackingHttpClient>();
var patchDocument = new JsonPatchDocument
{
new JsonPatchOperation
{
Operation = Operation.Add,
Path = "/fields/System.Title",
Value = "Sample work item created via .NET client with Microsoft Entra ID"
},
new JsonPatchOperation
{
Operation = Operation.Add,
Path = "/fields/System.Description",
Value = "This work item was created using the Azure DevOps .NET client library with Microsoft Entra ID authentication"
}
};
try
{
var workItem = await witClient.CreateWorkItemAsync(patchDocument, project, "Task");
return workItem;
}
catch (Exception ex)
{
Console.WriteLine($"Error creating work item: {ex.Message}");
throw;
}
}
エラー処理
アプリケーションでは、常に適切なエラー処理を実装します。
try
{
var response = await client.GetAsync(requestUri);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
// Process successful response
}
catch (HttpRequestException ex)
{
// Handle HTTP-related errors
Console.WriteLine($"HTTP Error: {ex.Message}");
}
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
{
// Handle timeout
Console.WriteLine("Request timed out");
}
catch (Exception ex)
{
// Handle other errors
Console.WriteLine($"Unexpected error: {ex.Message}");
}
ベスト プラクティス
- Microsoft Entra ID を使用する: 実稼働アプリケーションには、Microsoft Entra ID 認証を使用します
- HTTPS を使用する: API 呼び出しには常にセキュリティで保護された接続を使用する
- レート制限の処理: 指数バックオフを使用して再試行ロジックを実装する
- キャッシュ応答: 頻繁にアクセスされるデータを格納して API 呼び出しを減らす
- 特定の API バージョンを使用する: 破壊的変更を回避するために特定のバージョンにピン留めする
- 入力の検証: API 呼び出しを行う前に常にユーザー入力を検証する
- 適切にログを記録する: デバッグ用のログ API 操作が、資格情報をログに記録することはありません
- トークン管理: Microsoft Entra ID トークンの適切なトークン キャッシュと更新ロジックを実装する
AI を使用して REST API コードを生成する
エージェント モードで Azure DevOps MCP Server が AI エージェントに接続されている場合は、自然言語プロンプトを使用して、Azure DevOpsの REST API コードを生成できます。
| Task | プロンプトの例 |
|---|---|
| プロジェクトを一覧表示する | Show me how to list all projects in my Azure DevOps organization using the REST API with Microsoft Entra ID authentication in C# |
| 作業項目の作成 | Write a REST API call to create a bug in Azure DevOps with proper authentication headers and JSON-patch body |
| Git リポジトリを取得する | Create a C# HttpClient example that retrieves Git repositories from Azure DevOps using a Bearer token from MSAL |
| 作業項目フィールドを更新する | Show me how to update work item fields using the Azure DevOps REST API PATCH method with proper content type headers |
| WIQL を使用したクエリ | Write a REST API call to execute a WIQL query against Azure DevOps and deserialize the response |
| ページネーションの処理 | Show me how to handle continuation tokens when listing Azure DevOps resources with the REST API in C# |
注
エージェント モードと MCP サーバーでは自然言語が使用されるため、これらのプロンプトを調整したり、フォローアップの質問をして結果を絞り込むことができます。