One Tool, All APIs: Construct API Headers with PowerShell

This is the fourth post in the One Tool, All APIs: PowerShell series. Previous posts:

  1. One Tool, All APIs: PowerShell As The All-Purpose API Client
  2. One Tool, All APIs: API Authentication With PowerShell
  3. One Tool, All APIs: API Parameters with PowerShell

In today’s article, we will discuss API headers. In a nutshell, API headers contain additional information about the HTTP request or HTTP response. Additional information includes metadata like content type, authentication tokens, caching directives, etc.

RFC 7230 outlines the syntax and semantics of HTTP/1.1 messages, which includes headers and how they are structured within the HTTP protocol. HTTP headers consist of a name-value pair separated by a colon.  They are divided into general headers, request headers, response headers, and entity headers, each serving specific purposes.

Request and Response headers are dedicated each to HTTP request and response respectively, while general and entity headers can be used for both.

There isn’t an exhaustive, fixed list of headers, as new headers can be introduced via extensions and their usage can vary depending on the context. Here is a summary of the commonly used headers:

How to Craft API Headers with PowerShell

Both of our cmdlets Invoke-RestMethod and Invoke-WebRequest have -Headers parameter, which accepts header in Hashtable or Dictionary format.

Let’s look into the example.

Example

To showcase the headers usage we are going to interact with Microsoft Graph API. We will add all of the items we already discussed in the previous posts to the mix.

Goal: Get users by their job title.

API Endpoint URL: https://graph.microsoft.com/v1.0/users

Approach

#Authenticate
$tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$body = @{
    client_id     = $clientId
    scope         = "https://graph.microsoft.com/.default"
    client_secret = $secret
    grant_type    = "client_credentials"
}
$response = Invoke-RestMethod -Uri $tokenEndpoint -Method Post -Body $body
$accessToken = $response.access_token

#Craft search query
$resource = "https://graph.microsoft.com/"
$searchQuery = "jobTitle:Engineer"  # Search for users with job title as Engineer
$orderBy = "displayName asc"        # Sort results by display name in ascending order

#Craft headers
$headers = @{
    'Authorization'    = "Bearer $accessToken"
    'Content-Type'     = 'application/json'
    'ConsistencyLevel' = 'eventual'
    'OrderBy'          = $orderBy
}

#Submit Request
$userEndpoint = "https://graph.microsoft.com/v1.0/users?`$search=`"$searchQuery`""
$userData = Invoke-RestMethod -Uri $userEndpoint -Method Get -Headers $headers

#Parse response
foreach ($user in $userData.value) {
        Write-Host "User ID: $($user.id)"
        Write-Host "User Display Name: $($user.displayName)"
        Write-Host "Job Title: $($user.jobTitle)"
        Write-Host "-----"
}

Conclusion

As you can see, using PowerShell when you know what you are doing and more importantly, understand the end goal is like having the ultimate tool at your disposal. With PowerShell, you’re in control, making tasks smoother and achieving your goals with the style.

Next: Cookies & Session Control with PowerShell

Icons created by Freepik – Flaticon.

Thanks a lot for reading.

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.