Querying API’s using PowerShell Commands

It’s always useful to have these commands at your fingertips when you need to get or post some information to an API. I’m going to cover three of Microsoft API’s here.

  • Azure DevOps API
  • Azure Rest API
  • Azure Graph API

The Azure DevOps API is used to interact with Azure DevOps; you can create release definitions, create variable groups, create new projects, for example.

The Azure Rest API is used to interact with Azure resources; you can create a huge number of different resources – Resource Groups, Web Applications, Virtual Machines, Anything you can see in Azure can be created, destroyed via the API.

The Graph API is a central API which connects to many different services, such as, Azure Active Directory, Exchange, Sharepoint, to name a few.

To connect to the the following API’s I’m using PowerShell

Azure DevOps API

This one is quite straight forward. Login to Azure DevOps (ADO) and get a PAT (Personal Access Token) this can be done by clicking on User Settings in the top right-hand corner and selecting Personal Access Token.

Create a new one and set the permissions as you see fit. Copy down the token it gives you.

As an example, the code below will show you how to get a list of projects in your ADO and how to create a Project in ADO.

To start, create a file, call it whatever you want, but make the extension a ps1. e.g. powershellapi.ps1. Copy the code below into the file.

In the code below, you can see a user variable – $user. This is to be left empty. ADO uses the PAT as the password so go ahead and paste it in the $token variable.

For ease, I’ve separated each action in a function so that you can rerun the command.

You need to fill in the following variables –

  • $Token = PAT
  • $projectName = “The Project Name”
  • $organization = “The Organisation name”
  • $description = “The description of the project”
# PowerShellAPI.ps1

# Used to authenicate to the API
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $User, $Token)))

$user = "" # Name of the user. THIS IS SUPPOSED TO BE EMPTY, LEAVE IT EMPTY
$token = "" # THIS IS WHERE YOU ADD YOUR PAT - PERSONAL ACCESS TOKEN
$organization = "" # put in the name of the organisation as shown in ADO
$projectName = "BeHappy" # Call this whatever you want
$description = "A project to make you happy" # add whatever you want to the description

function listProjects {

# API URI GET - Gets a list of projects
$listProjectsURI = "https://dev.azure.com/${organization}/_apis/projects?api-version=6.0"

# Invoke the get and return the answer
$listProjectsResult = Invoke-RestMethod -Uri $ListProjectsURI -Method get -ContentType "application/json" -Headers @{Authorization = ("Basic {0}" -f $base64AuthInfo) }
return $listProjectsResult.value.Name
}


function createProject {


# API URI POST - Creates a new project
$createProjectURI = "https://dev.azure.com/${organization}/_apis/projects?api-version=6.0"

 $Body = @{
          'name'= $projectName
          'description' = $description
          'capabilities' = @{
              'versioncontrol' = @{
                  'sourceControlType' = "Git"
              }
              'processTemplate' = @{
                  "templateTypeId" = "6b724908-ef14-45cf-84f8-768b5384da45"
              }
          }
  }

$Body = $Body | convertto-json

$createProjectResult = Invoke-RestMethod -Uri $createProjectURI -Method post -body $Body -ContentType "application/json" -Headers @{Authorization = ("Basic {0}" -f $base64AuthInfo) }    
return $createProjectResult
}

This was an example of using PowerShell to GET or POST information from/ to the Azure DevOps API.

Azure REST API (Azure Resource Manager)

With the ARM API, you can create all of the resources that you do through the portal. Below is an example of fetching the list of Resource Groups and of creating a Resource Group. You will need to create, if you don’t already have, an app registration. This is used to authenticate. This can be done in Azure Active Directory, under App registrations.

You will need the following-

  • The Application ID from the App registration
  • The Application Secret from the App registration
  • The Subscription ID – search for subscriptions in the ARM portal
  • The Tenant ID – in Azure Active Directory, properties
  • and a Resource Group Name – can be whatever you want it to be
# PowerShellARMAPI.ps1

$ClientID       = ""        # fill in the Application ID
$ClientSecret   = ""    # fill in the Application secret
$Tenant_id      = ""        # fill in the tenant ID
$subscriptionid = ""  # fill in the subscription ID
$resourceGroupName = "AResourceGroupName"   # fill in the name of the resource group you want.
function getBearer([string]$TenantID, [string]$ClientID, [string]$ClientSecret)
{
  $TokenEndpoint = {https://login.windows.net/{0}/oauth2/token} -f $TenantID 
  $ARMResource = "https://management.core.windows.net/";

  $Body = @{
          'resource'= $ARMResource
          'client_id' = $ClientID
          'grant_type' = 'client_credentials'
          'client_secret' = $ClientSecret
  }

  $params = @{
      ContentType = 'application/x-www-form-urlencoded'
      Headers = @{'accept'='application/json'}
      Body = $Body
      Method = 'Post'
      URI = $TokenEndpoint
  }

  $token = Invoke-RestMethod @params

  Return "Bearer " + ($token.access_token).ToString()
}

$token = getBearer $Tenant_id $ClientID $ClientSecret

# Now we have the bearer - so we can authenicate 

function getRGs {
# Get a list of resource groups in your subscription

$getRGList = "https://management.azure.com/subscriptions/$subscriptionid/resourcegroups?api-version=2020-06-01"

$headers = @{
    'Host' = 'management.azure.com'
    'Content-Type' = 'application/json'
    'Authorization' = "$token"
   }

# Invoke the get and return the result
$getRGListResult = Invoke-RestMethod -Uri $getRGList -Method get -Headers $headers
return $getRGListResult 
}


function createRG {
# This example adds a resource group called Deathrace300

$createRG = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/" + $resourceGroupName + "?api-version=2020-06-01"

$body = @{
    "location" = "uksouth"
}

$body = ConvertTo-Json $body
 
$headers = @{
    'Host' = 'management.azure.com'
    'Content-Type' = 'application/json'
    'Authorization' = "$token"
    }
 
# Invoke the get and return the result
$CreateRGResult = Invoke-RestMethod -Uri $createRG -Method put -Headers $headers -Body $Body
return $CreateRGResult
}

I’ve separated the actions into functions again, so you can easily test the code. If you want to save the results, when you run the functions add a variable at the start e.g.

$result = getRGs

This allows you to keep the result and also query the variable. So if you wanted to return the names of the Resource Groups, you could type.

$result.value.name

This was an example of accessing the ARM API using PowerShell

Microsoft Graph API

Sidenote: There is a PowerShell module for the Graph. It’s worth a look. To install it, do the following in a PowerShell Terminal.

install-module Microsoft.Graph
import-module Microsoft.Graph

To list all the available commands in the module, first, run the get-modules and then you can see all of the available options for Microsoft.Graph. If for example, you wanted to see all of the commands for users.

get-modules
get-command -module microsoft.graph.users

If you wanted to see all the commands

get-command -module microsoft.graph.*

Anyway, back to the Graph API

This API requires an application, like the ARM API. You will need to set the permissions in the App Registration, go into the application, click on API Permissions and Add a permission.

Next select Microsoft Graph,

Then select Application permissions,

Finally, you will see a list of permissions. For the example below, you will need the user’s permissions to write and read. If you are unsure, just for this test, give all of the user’s permissions expect the invite guest permission.

Once selected and saved. Then grant admin consent for company name

Now we can get back to the code. Again I’ve separated the actions to functions. The first function gets all the users from Azure Active Directory and the second function adds users to Azure Active Directory

The following variables are required-

  • $ClientID = Application ID
  • $ClientSecret = Application secret
  • $tenantName = the domain name when you first setup Azure AD. companyname.onmicrosoft.com
  • $displayname = the name of the user
#Microsoft Graph API

# Input Parameters  

$ClientID       = ""  
$ClientSecret   = ""
$tenantName = "XXX.onmicrosoft.com" # use get-aztenant to find the name and use the companyname.onmicrosoft.com  
$resource = "https://graph.microsoft.com/v1.0/"  


  
$tokenBody = @{  
    Grant_Type    = "client_credentials"  
    Scope         = "https://graph.microsoft.com/.default"  
    Client_Id     = $clientId  
    Client_Secret = $clientSecret  
}   
  
$tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token" -Method POST -Body $tokenBody  


function getusers{
    $getusersURI = $resource + "users"
    $headers = @{
        Authorization = "Bearer $($tokenResponse.access_token)"
    }

    $result = Invoke-RestMethod -Headers $headers -Uri $getusersURI -Method Get  
    ($result | select-object Value).Value | Select-Object id, displayName, visibility  
}


function createuser {
$displayname = "XXX"
$createuserURI = $resource + "users"
$headers = @{
    Authorization = "Bearer $($tokenResponse.access_token)"
}

$body = @{
    "accountEnabled" = 'true'
    "displayName" = $displayname
    "mailNickname" = $displayname
    "userPrincipalName" = $displayname + "@" + $tenantName
    "passwordProfile" = @{
      "forceChangePasswordNextSignIn" = 'true'
      "password" = "ALONGandComPl3xPASS123word!"
    }
  }
$body = convertto-json $body
  $result = Invoke-RestMethod -Headers $headers -Uri $createuserURI -Method Post -Body $body -ContentType "application/json"
($result | select-object Value).Value | Select-Object id, displayName, visibility  

}

This was an example of using PowerShell to query Microsoft Graph API.

I hope these examples will help you to understand how to query API using PowerShell and be simlpe enough for you to expand on.

Thanks for reading, if you liked the article, please leave a comment.