Search code examples
c#azureazure-rest-api

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.


Solution

  • 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.