Cannot PATCH DNS record

I am trying to update a specific DNS record with the http API however I am getting an error.

Using this endpoint to update an existing record

https://developers.cloudflare.com/api/operations/dns-records-for-a-zone-patch-dns-record]

However I get the error:

{
  result: null,
  success: false,
  errors: [ { code: 9207, message: 'Request body is invalid.' } ],
  messages: []
}

The code I am using is this:

const TOKEN = '<API_TOKEN>'
const ZONE_ID = '<ZONE_ID - From web dashboard'
const DNS_RECORD_NAME = 'subdomain.example.com'
let dns_record_id = ''

// Get DNS_RECORD_ID by listing all records and finding the id of the record I am after
// In reality I would not repeat this again once the id was determined
// Just want to know that I am using the correct "id" in the request
let records = await fetch(`https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records`, {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${TOKEN}`,
    }
}).then(r => r.json())

for (let record of records.result) {
  if (record.name === DNS_RECORD_NAME) {
    dns_record_id = record.id
    break
  }
  throw new Error('Record does not exist')
}

// Get an IP to update the current one with
// In future don't update cloudflare unless the IP is different
let update_ip = (await fetch('http://ipv4.icanhazip.com').then(r => r.text())).trim()

// Update record in Cloudflare
let response = await fetch(`https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records/${dns_record_id}`, {
    method: 'PATCH',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${TOKEN}`,
    },
    data: JSON.stringify({
      "content": update_ip,
      "name": DNS_RECORD_NAME,
      "proxied": false,
      "type": "A",
      "comment": "",
      "tags": [],
      "ttl": 60
    })
})

console.log(await response.json())

I should mention that the first request to list the records works fine. I get a JSON back with the results: Array<Record>.

It’s the PATCH request that fails with the error

You want to use

body: JSON.stringify({
      "content": update_ip,
      "name": DNS_RECORD_NAME,
      "proxied": false,
      "type": "A",
      "comment": "",
      "tags": [],
      "ttl": 60
    })

Instead of data field.

1 Like

Oh my god… :man_facepalming:

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.