-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHelper.ImportApiAsync.cs
56 lines (47 loc) · 2.03 KB
/
Helper.ImportApiAsync.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using Azure.Identity;
using Azure.Core;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.Models;
using Microsoft.Rest;
partial class Helper
{
public static async Task ImportApiAsync(string tenantId, string subscriptionId, string resourceGroupName, string serviceName,
string apiId, string apiFilePath)
{
if (!File.Exists(apiFilePath))
{
throw new FileNotFoundException("File not found.", apiFilePath);
}
// Authenticate interactively using Azure Identity
var serviceClientCredentials = await GetServiceClientCredentialsAsync(tenantId);
// Create the ApiManagementClient
using var client = new ApiManagementClient(serviceClientCredentials) { SubscriptionId = subscriptionId };
var apiContent = File.ReadAllText(apiFilePath);
try
{
await client.Api.CreateOrUpdateAsync(resourceGroupName, serviceName, apiId, new ApiCreateOrUpdateParameter
{
Format = ContentFormat.Openapijson,
Value = apiContent,
Path = apiId,
DisplayName = $"Graph L - {apiId}",
});
Console.WriteLine($"Successfully imported API '{apiId}' from file '{apiFilePath}'.");
}
catch (Exception e)
{
Console.WriteLine($"Failed importing API '{apiId}' from file '{apiFilePath}'. Exception: {e.Message}.");
}
}
private static async Task<ServiceClientCredentials> GetServiceClientCredentialsAsync(string tenantId)
{
var tokenCredential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
{
TenantId = tenantId
});
// Get the access token for Azure Management
var tokenRequestContext = new TokenRequestContext(new[] { "https://management.azure.com/.default" });
var token = await tokenCredential.GetTokenAsync(tokenRequestContext);
return new TokenCredentials(token.Token);
}
}