Powershell Invoke-RestMethod
I'm trying to create a powershell script to access the DYN API and perform checks / updates on the DNS zones I'm using / test.
I am following their given API and here's the first link, https://help.dyn.com/session-log-in/
Here's the start of the REST script I put together:
$url = "https://api2.dynect.net/REST/Session/"
$body = @{customer_name='mahcompany';user_name='mahname';password='mahpass'}
Invoke-RestMethod -Method Post -Uri $url -Body $body
This leads to the following results:
Invoke-RestMethod: The remote server responded with an error: (406) Not valid. On line: 12 char: 9 + $ test = Invoke-RestMethod -Method Post -Uri $ url -Body $ body + ~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~ + CategoryInfo: InvalidOperation: (System.Net.HttpWebRequest: HttpWebRequest) [Invoke-> RestMethod], WebException + FullyQualifiedErrorId: WebCmdletWebResponseException, Microsoft.PowerShell.Commands.InvokeRestMethodCommand
It is supposed to be a JSON request as per DYN info, so I tried other DYN examples using CURL as a basis:
$json = @"{"customer_name":"yourcustomer","user_name":"youruser","password":"yourpass"}'
However, that doesn't work either.
Can anyone point me in the right direction? It can't be crazy, I am just trying to pass parameters to the request string of the rest method. Any help would be very much appreciated at this point.
-Sean
source to share
content type
Invoke-RestMethod -Method Post -Uri $url -Body $body -ContentType 'application/json'
This can be a problem if dyn.com expects the correct content type.
According to the documentation on Invoke-RestMethod
:
If this parameter is omitted and the request method is POST, Invoke-RestMethod sets the content type to "application / x-www-form-urlencoded". Otherwise, the content type is not specified in the call.
ConvertTo-JSON
You don't need to manually create the JSON string. You can create a hash table and then convert it:
$data = @{ customer = 'something' name = 'whatever' } $data | ConvertTo-JSON
I am not saying that you are definitely making the wrong JSON, but it can help prevent this.
source to share