I can use curl to call a REST api
curl -H 'Authorization: Bearer <token>' \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-X POST \
-d '<json>' \
https://api.dnsimple.com/v2/1010/zones/example.com/records
and the json needs to be in the format of:
{
"name": "",
"type": "MX",
"content": "mxa.example.com",
}
How can I call this API using Invoke-WebRequest? I'm trying the following (of course I'm using variables here) When I call this I'm getting an error 400
$uri = [string]::Format("https://api.dnsimple.com/v2/{0}/zones/{1}/records",$account,$domain)
$headers = @{}
$headers["Authorization"] = [string]::Format("Bearer {0}", $token)
$headers["Accept"] = "application/json"
$headers["Content-Type"] = "application/json"
$json = @{}
$json["name"] = $subdomain
$json["type"] = "A"
$json["content"] = $ip
Invoke-WebRequest -Uri $uri -Body $json -Headers $headers -Method Post
Problem seems to be that you're passing a raw hashtable to the -Body
parameter, rather than an actual valid JSON string. Use ConvertTo-Json
for this. Also, no need to use [string]::Format()
explicitly, you can use the -f
operator instead!
$uri = 'https://api.dnsimple.com/v2/{0}/zones/{1}/records' -f $account,$domain
$headers = @{
Authorization = 'Bearer {0}' -f $token
Accept = 'application/json'
Content-Type = 'application/json'
}
$json = @{
name = "$subdomain"
type = "A"
content = "$ip"
} |ConvertTo-Json
Invoke-WebRequest -Uri $uri -Body $json -Headers $headers -Method Post
I'd use Invoke-RestMethod personally...
See
Saves re-inventing the wheel.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.