3

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
1
  • 1
    -Body $json -> -Body ($json |ConvertTo-Json) Commented Jan 22, 2017 at 9:13

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

-2

I'd use Invoke-RestMethod personally...

See Get-Help Invoke-RestMethod -Examples

Saves re-inventing the wheel.

1 Comment

This should be a comment, as it doesn't actually attempt to answer the question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.