Testing REST API with PowerShell
Here is a simple way to test a REST API with PowerShell. All api.example.com addresses below are documentation placeholders, not working API endpoints. Replace them only with an API you are authorized to test, and use a test environment: a POST can change server data. The original https://path/to/api and https://google.com/api/GetData strings were illustrative, not verified service endpoints. IANA reserves example domains for documentation.
Invoke-RestMethod -Uri 'https://api.example.com/resource' -Method Post -ContentType 'application/json' -Body '{ "key": "val" }'
To display the parsed response object as readable JSON, append this pipeline segment to the preceding command. -Depth 10 limits how deeply nested objects are serialized; choose a depth appropriate to the response rather than assuming ten levels cover every result. This reserializes the object, not necessarily the original response bytes. See ConvertTo-Json.
| ConvertTo-Json -Depth 10
When the response is parsed as an XML document, store it in a variable and use OuterXml to display the node and its descendants. The example below is a GET for XML, not a complete SOAP request: SOAP calls need the service’s required HTTP method, envelope, headers and content type. See XmlNode.OuterXml and SOAP’s HTTP binding.
$result = Invoke-RestMethod -Uri 'https://api.example.com/xml-resource'
if ($result -is [System.Xml.XmlNode]) {
$result.OuterXml
} else {
throw 'The response was not parsed as an XML node.'
}
For a GET that requires Basic authentication, PowerShell can construct the Authorization: Basic header locally. This example targets PowerShell 7.x; -Authentication was added in PowerShell 6 and is unavailable in Windows PowerShell 5.1. Check your version with $PSVersionTable.PSVersion. The guard stops the example before prompting while the placeholder is unchanged. See Invoke-RestMethod.
# PowerShell 7.x. Replace this placeholder with your authorized HTTPS API.
$uri = [uri]'https://api.example.com/GetData'
if ($uri.Scheme -ne 'https' -or $uri.Host -eq 'api.example.com') {
throw 'Set $uri to your trusted HTTPS API before entering credentials.'
}
$credential = Get-Credential
Invoke-RestMethod -Method Get -Uri $uri -Authentication Basic -Credential $credential
The original article linked to this third-party Basic header generator. The link is retained for provenance, not as a recommendation to enter real credentials. Do not paste real passwords, API secrets or authorization headers into online generators. Use the local credential prompt above for a trusted HTTPS endpoint and follow that service’s authentication requirements. Basic uses Base64 encoding, not encryption; protect the connection with TLS and never log or publish the resulting header. See RFC 7617.