PowerShell by Patrik

Adding Headers to PowerShell Web Requests Made Simple

Calling web services is common in automation, monitoring, and integration tasks. Many APIs expect extra information in the request, such as authentication tokens, data formats, or custom settings. This information is sent through headers. Once you understand how headers work in PowerShell, you can safely connect to most modern services and build reliable scripts with confidence.

Why Headers Matter

Headers describe how the server should handle your request. They can:

  • Identify who you are (authentication)
  • Tell the server what data format you send or expect
  • Enable special features or versions of an API

Without the correct headers, a request may fail or return unexpected data.

How PowerShell Handles Headers

PowerShell uses a simple key-value structure called a hashtable. Each key is the header name, and the value is the header content. This hashtable is passed to the request using the -Headers parameter.

Example: Add One Header

$headers = @{
    "Authorization" = "Bearer YOUR_TOKEN"
}

Invoke-RestMethod -Uri "https://api.example.com/data" -Headers $headers

Example: Add Multiple Headers

$headers = @{
    "Authorization" = "Bearer YOUR_TOKEN"
    "Content-Type"  = "application/json"
    "Accept"        = "application/json"
}

Invoke-RestMethod -Uri "https://api.example.com/data" -Method Get -Headers $headers

Example: Send Data with Headers (POST)

$headers = @{
    "Content-Type" = "application/json"
}

$body = @{
    name = "Sample"
    value = 123
} | ConvertTo-Json

Invoke-RestMethod -Uri "https://api.example.com/items" -Method Post -Headers $headers -Body $body

Key Takeaway

Create a hashtable for headers and attach it using -Headers. This approach works for most APIs and keeps your scripts clean, readable, and easy to maintain.

 

powershell
api
headers
scripting
automation

Comments