Vinny
Vinny

Reputation: 629

How to call Azure Rest API in C#

I'm new to C# world. I have a project where I need to collect Azure compute usage quotas across all regions from 700+ subscriptions. I have done it easily using PowerShell (Get-AzVMUsage).

I have to do it using C#. I guess I need to use Rest API for it. (I am open to another way to achieve this).

Azure Rest API: GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/usages?api-version=2019-12-01

How can I fetch results using the above Rest API? Once I get results from this Rest API, I can put my business logic on top of it to perform data aggregations and loop it through 700+ Subscriptions and dump the data in SQL-MI.

Upvotes: 5

Views: 14939

Answers (3)

John
John

Reputation: 30576

The answer from Vinny is no longer supported. As of December 2022 Microsoft.IdentityModel.Clients.ActiveDirectory Nuget which is used with AuthenticationContext is no longer supported.

We can use the Azure.Identity Nuget and then replace the GetAccessToken method with this...

private static async Task<string> GetAccessToken(string tenantId, string clientId, string clientKey)
{
    Console.WriteLine("Begin GetAccessToken");

    var credentials = new ClientSecretCredential(tenantId, clientId, clientKey);
    var result = await credentials.GetTokenAsync(new TokenRequestContext(new[] { "https://management.azure.com/.default" }), CancellationToken.None);
    return result.Token;
}

That said it may be easier to use the SDKs. I have written a blog post on both the SDKs and Rest APIs that you may find useful.

Upvotes: 4

Vinny
Vinny

Reputation: 629

I Google'ed and figured out the way from below url.

https://learn.microsoft.com/en-us/archive/blogs/benjaminperkins/how-to-securely-connect-to-azure-from-c-and-run-rest-apisMSDN Forum

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;

namespace AzureCapacityUsage
{
    class Program
    {
        static async Task Main()
        {            
            try 
            {
                string token = await GetAccessToken(TenantID,ClientID,Password); 
                await GetResults(token);              
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception: {ex.Message}");
            }
        }

        private static async Task<string> GetResults(string token)
        {
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://management.azure.com/subscriptions/")
            };

            string URI = $"{SubscriptionGUID}/providers/Microsoft.Compute/locations/{Region}/usages?api-version=2019-12-01";

            httpClient.DefaultRequestHeaders.Remove("Authorization");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            HttpResponseMessage response = await httpClient.GetAsync(URI);

            var HttpsResponse = await response.Content.ReadAsStringAsync();
            var JSONObject =  JsonConvert.DeserializeObject<object>(HttpsResponse);
            
            Console.WriteLine(JSONObject);
            var JSONObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(JSONObject);
            return response.StatusCode.ToString();

        }
        private static async Task<string> GetAccessToken(string tenantId, string clientId, string clientKey)
        {
            Console.WriteLine("Begin GetAccessToken");

            string authContextURL = "https://login.windows.net/" + tenantId;
            var authenticationContext = new AuthenticationContext(authContextURL);
            var credential = new ClientCredential(clientId, clientKey);
            var result = await authenticationContext

            .AcquireTokenAsync("https://management.azure.com/", credential);
            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }
            string token = result.AccessToken;
            return token;
        }
    }
}

Upvotes: 7

Heikki
Heikki

Reputation: 25

System.Net.HttpClient is your friend here :

using System.Net.Http;
using System.Threading.Tasks;

namespace Sandbox
{
    public class SampleCall
    {
        static async Task<string> CallApi()
        {
            var subscriptionId = "subscriptionIdHere";
            var location = "locationHere";
            var uri = $"https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/usages?api-version=2019-12-01";

            using var client = new HttpClient();
            var response = await client.GetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }

            return string.Empty;
        }
    }
}

Usage :

var content = await SampleCall.CallApi();

Upvotes: -3

Related Questions