How to call Azure Rest API in C#

Viewed 7497

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.

2 Answers

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

https://docs.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;
        }
    }
}

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();
Related