How to call Azure REST APIs with PowerShell

In this blog post, we will walk you through the steps of calling Azure REST APIs with PowerShell.

Azure REST APIs are a powerful way to interact with Azure resources, but using them can be a challenge for those who are not familiar with the process. PowerShell, on the other hand, is a scripting language that is widely used for automation and administration tasks in Windows environments. By combining PowerShell with Azure REST APIs, you can easily automate tasks and manage your Azure resources

Benefits of Using Azure REST API

The main benefit of using Azure REST API is that it offers extra configuration items of Azure using programming tools because the API is capable of configuring every resource in Azure and its attributes which is not always the case with the Az PowerShell module or Azure CLI.

Run REST API

The following PowerShell script will use a REST API call to list all the available Web App stacks for a Linux App Service plan. The URL to the API is here

# Connect to Azure

Connect-AzAccount

# Get authentication token
$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
}

# REST API Call URI
$restUri='https://management.azure.com/providers/Microsoft.Web/availableStacks?osTypeSelected=Linux&api-version=2022-03-01'


# Invoke REST API Call 
Invoke-RestMethod -Uri $restUri -Method Get -Headers $authHeader  | ConvertTo-Json 

The above code will authenticate to Azure first and acquire an authentication token. The variable $restapi has the REST API URI for the get request.

The last line invokes the request and converts it to a Json format.


Posted

in

, ,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.