PowerShell - REST API
- Invoke-WebRequest
- Invoke-RestMethod
Invoke-WebRequest: This command can be used to get content from a web page. The cmdlet sends HTTP calls to a web page or a web server.
Using Basic Authentication:
$creds = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes('username:password'))
Invoke-WebRequest
-URI '<path>'
-Method 'POST'
-ContentType 'application/json; charset=utf-8'
-Headers @{'Accept' = 'application/json'; 'Sample-Header' = 'Test'}
-Authentication @{ 'Authorization' = 'Basic ' + $creds }
Using a Client Certificate:
Invoke-WebRequest
-URI '<path>'
-Method 'POST'
-ContentType 'application/json; charset=utf-8'
-Headers @{'Accept' = 'application/json'; 'Sample-Header' = 'Test'}
-CertificateThumbprint 934367bf1c97033f877db0f15cb1b586957d313
Using Windows authentication:
Invoke-WebRequest
-URI '<path>'
-Method 'POST'
-ContentType 'application/json; charset=utf-8'
-Headers @{'Accept' = 'application/json'; 'Sample-Header' = 'Test'}
-UseDefaultCredentials
try {
$result = Invoke-WebRequest -URI '<path>'
-Headers @{'Accept' = 'application/json'; 'Sample-Header' = 'Test'}
-Authentication @{ 'Authorization' = 'Basic ' + $creds }
-Method 'POST'
}
catch {
$result = $_.Exception
}
$params = @{
uri = 'rest-api-url';
Method = 'GET';
Headers = @{ 'Authorization' = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("username:password"))}
}
$response = Invoke-RestMethod @params
Difference between Invoke-WebRequest and Invoke-RestMethod:
Invoke-RestMethod understands REST APIs better that IWR and it parses the JSON into meaningful PowerShell objects. Invoke-RestMethod is a superset of Invoke-WebRequest and it is often used for accessing REST API resources.
Comments
Post a Comment