DevOps | Scripts | Automation

Azure

How to use Azure REST API in PowerShell?

There are multiple ways to work with Azure and Azure rest API is one of them. To start with Azure API, we first need to connect to the Azure Account. You can use the Connect-AzAccount to connect your azure account. Once you are connected to the Azure Account, now lets say you need to retrieve the list of the Azure Virtual Machines using the rest API, you can use the below URL.

Azure Rest API

Below is the URL to list all the VMs of the Azure Cloud.

https://docs.microsoft.com/en-us/rest/api/compute/virtual-machines/list-all

and URL for this is below.

https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachines?api-version=2021-03-01

Generate Bearer Token

Before using the above URL, we need to authenticate Azure Rest API with the connected account and for that we need the bearer token and to obtain the bearer token we need to use the below command.

# Log in first with Connect-AzAccount if not using Cloud Shell

$azContext = Get-AzContext
$azProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
$profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($azProfile)
$token = $profileClient.AcquireAccessToken($azContext.Subscription.TenantId)
$authHeader = @{
    'Content-Type'='application/json'
    'Authorization'='Bearer ' + $token.AccessToken
}

Once we have this Azure header available we can pass this as the header in Invoke-WebRequest or Invoke-RestMethod API.

Get Azure Subscription ID

Now to list the VMs, we need to provide the subscription ID in the URL above. If you don’t know the subscription ID, use the Get-AzSubscription command and you can find the respective subscription ID for the Azure Subscription. I have the already one so I can directly use it in my URL.

Invoke-RestMethod to work with Azure Rest API

$restUri =  "https://management.azure.com/subscriptions/xxxx-xxxx-xxx/providers/Microsoft.Compute/virtualMachines?api-version=2021-03-01"
$response = Invoke-RestMethod -Uri $restUri -Method Get -Headers $authHeader

Output:

You can further expand output as shown below

You can use any Azure Rest API to work with and use POST or GET method.