FrankU32
FrankU32

Reputation: 341

Issues with PowerShell generated JSON and CloudFlares API

I am trying to write some PowerShell to update an 'A' record on my Cloudflare account. The code looks like the following:

##Configure headers
$Bearer = "Bearer " + $cloudflareAPIToken
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("Authorization",$Bearer)

##Configure Payload
$Body = @{
    type = 'A'
    Name = 'homepc'
    Content = '8.8.8.8'
    ttl = 1}

$Jsonbody = $Body | ConvertTo-Json -Compress

Invoke-RestMethod -Method PUT "https://api.cloudflare.com/client/v4/zones/$DNSZoneID/dns_records/$ARecordID"  -Headers $Headers -Body -$Jsonbody -ContentType 'application/json'

And I am getting the error

Invoke-RestMethod: {"result":null,"success":false,"errors":[{"code":9207,"message":"Content-type must be application/json."}],"messages":[]}

My json payload looks like this

PS C:\Users\Frank> $Jsonbody

{"type":"A","Name":"homepc","ttl":1,"Content":"8.8.8.8"}

If I cut and paste this payload into Postman then it works. Bellow is the code generated by Postman. This works

curl --location --request PUT 'https://api.cloudflare.com/client/v4/zones/6b5e4cf4634bc20cebc1cd96072c/dns_records/4cb90f1dabfcc63a97055234520' \
--header 'Authorization: Bearer zHl3LhnQzRyw1_' \
--header 'Content-Type: application/json' \
--data-raw '{"type":"A","Name":"homepc","Content":"8.8.8.8","ttl":1}'

Can anyone help me get to the bottom of this?

Thank in advance

Frank

Upvotes: 1

Views: 551

Answers (1)

Mark Elvers
Mark Elvers

Reputation: 647

I don't use CloudFlare but from the error message it looks like you are missing the Content-Type header. Try adding this line:

$Headers.Add('Content-Type', 'application/json')

Edit: The header isn't needed as it was specified using -ContentType parameter to Invoke-RestMethod. On closer inspection of the command line the parameter -Body -$Jsonbody has an erroneous - in front of the JSON body variable which made the string that was sent -{....}.

Upvotes: 4

Related Questions