Adding Bulk DNS with the API

I created an API to connect to my Cloudflare zone. I tested the API token and it works. Now when I try to add multiple domains with the API command that CLOUDFLARE provides it does not work. Keep getting an error message. Any see what is going on here. Here is the API command that Cloudflare provides that is not working I keep getting this error message.

{“success”:false,“errors”:[{“code”:6003,“message”:“Invalid request headers”,“error_chain”:[{“code”:6103,“message”:“Invalid format for X-Auth-Key header”}]}],“messages”:[],“result”:null}

for domain in $(cat domains.txt); do
printf “Adding ${domain}:\n”

curl https://api.cloudflare.com/client/v4/zones \
  -H 'Content-Type: application/json' \
  -H 'X-Auth-Email: <CLOUDFLARE_EMAIL>' \
  -H 'X-Auth-Key: <CLOUDFLARE_API_KEY>' \
  --data '{
  "account": {
    "id":"<ACCOUNT_ID" 
  },
  "name": "'"$domain"'",
  "type": "full"
}'

printf “\n\n”
done

Are you using an API token or your global API Key?

I created a API Token to just edit DNS. I can use global API Key if I have to.

Then you’ll want to use a single header of Authorization: Bearer <api token> rather than both the X-Auth-Email and X-Auth-Key headers.

2 Likes

Thanks. I was able to get it to work.

1 Like

@Cyb3r-Jak3 I was able to add 1 domain in my domain.txt file. Whenever I add more than 1 domain in the list it only adds the one at the bottom of the list. The rest gives me this error message.

[{“code”:6007,“message”:“Malformed JSON in request body”}],“messages”:[],“result”:null}

I’m also using GitBash in windows to run the API in the first post.

Can you share your request body?

Sure. Here it is.

for domain in $(cat domains.txt); do
printf “Adding ${domain}:\n”

curl https://api.cloudflare.com/client/v4/zones \
  -H 'Content-Type: application/json' \
  -H 'X-Auth-Email: <CLOUDFLARE_EMAIL>' \
  -H 'X-Auth-Key: <CLOUDFLARE_API_KEY>' \
  --data '{
  "account": {
    "id":"<ACCOUNT_ID" 
  },
  "name": "'"$domain"'",
  "type": "full"
}'

printf “\n\n”
done

My guess is the quoiting here is breaking the JSON.

Should I remove that line?

You don’t need to remove the line, but you need to maybe remove the single quotes there.

OK but it works fine when I just have one domain in the the domain.txt file.

Maybe the line break characters are causing issues with the JSON

So I removed the single quotes and now I get this error message. Weird…

[{“code”:1002,“message”:“Invalid domain”}],

Here is a picture of the output. There were 2 domains in the domain.txt file and as you can see the bottom domain is the only one that got added.

Can you add set -xe at the top of your bash script and run it? It should show the curl command being run, which will help view the JSON body being sent.

1 Like

Ok I added set -xe. Same thing. I can only add one domain at a time. Even if I put 2 domains in the domains.txt file the first one comes out with the MALFORMED JSON and the 2nd one gets added with no problems.