Activity: Scripting GET Requests

A GET request is the simplest API call being made. You can make the call with no additional filter and most API will respond with a small subsection.

We will use the script as an example in the previous page.

  1. Copy this code block below. Replace the text in block with details from your Office 365 Tenant.
#The Client ID from App Registrations
$clientId = "CLIENT_ID"
#The Tenant ID from App Registrations
$tenantId = "TENANT_ID"
#The Client ID from certificates and secrets section
$clientSecret = 'CLIENT_SECRET'

# Construct the authentication URL
$uri = "$tenantId/oauth2/v2.0/token"
# Construct the body to be used in Invoke-WebRequest
$body = @{
    client_id     = $clientId
    scope         = ""
    client_secret = $clientSecret
    grant_type    = "client_credentials"
# Get Authentication Token
$tokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType "application/x-www-form-urlencoded" -Body $body -UseBasicParsing
# Extract the Access Token
$token = ($tokenRequest.Content | ConvertFrom-Json).access_token

#The Graph API URL
$uri = ""
$method = "GET"
# Run the Graph API query to retrieve users
$output = Invoke-WebRequest -Method $method -Uri $uri -ContentType "application/json" -Headers @{Authorization = "Bearer $token"} -ErrorAction Stop

# Manipulate the JSON object in memory to be human readable

$users = ($users = ($output.Content | ConvertFrom-Json).value)
  1. Save the file as get-users.ps1
  2. Open a PowerShell terminal and navigate to the saved file location.
  3. Execute the file from the location it is saved by typing its name and pressing enter.

Adding a filter to the GET query.

  1. You can modify the URI with a filter in order to get more specific results. For the above query you could filter according to userName. (Replace with a username in your tenant.)
$uri = "$filter=userName eq ''"
  1. Update your script from the previous activity and observe the outcome. You can also use Graph Explorer to test filters before entering them into your script.