Skip to content

Instantly share code, notes, and snippets.

@Suzhou65
Last active July 24, 2024 13:35
Show Gist options
  • Save Suzhou65/8b9e5e5360f9c0a363e82038bb0d29b8 to your computer and use it in GitHub Desktop.
Save Suzhou65/8b9e5e5360f9c0a363e82038bb0d29b8 to your computer and use it in GitHub Desktop.
Get DNS record from CloudFlare API

Let's try to ask DNS record for CloudFlare API.

Replace the "API Token" at auth_key by the API Token you get, the "Zone ID" can be found in Cloudflare Dashboard, logged in the Cloudflare Dashboard, check the Domain page, "Zone ID" information will appearance at API block, right hand side.

import json
import requests

cloudflare_api = "https://api.cloudflare.com/client/v4/"
zone_id = "278035ad7a9d983bc54a990b43ef7eb0"
auth_key = "API Token"
headers = {'Authorization': auth_key, 'Content-Type':'application/json'}

cloudflare_dns = cloudflare_api + "zones/" + zone_id + "/dns_records"  
cloudflare_dns_respon = requests.get(cloudflare_dns, headers=headers)

if cloudflare_dns_respon.status_code == 200:
    print("Ok")
else:
    print(cloudflare_dns_respon.status_code)    

dns_data = json.loads(cloudflare_dns_respon.text)

If the request send successfully, the result will print.

Ok

Then, the JSON data(dns_data) it respon will be like this:

{'result': [{'id': '3f7a9d18e117a65860dc5e2f2abdd191',
   'zone_id': '278035ad7a9d983bc54a990b43ef7eb0',
   'zone_name': 'lewd.dream',
   'name': 'lewd.dream',
   'type': 'A',
   'content': '114.514.19.19',
   'proxiable': True,
   'proxied': True,
   'ttl': 1,
   'locked': False,
   'meta': {'auto_added': False,
    'managed_by_apps': False,
    'managed_by_argo_tunnel': False,
    'source': 'primary'},
   'created_on': '2020-08-24T03:30:28.114514Z',
   'modified_on': '2020-08-24T03:30:28.114514Z'},
  {'id': 'ec8b33016fccf46dc8969316578974d7',
   'zone_id': '278035ad7a9d983bc54a990b43ef7eb0',
   'zone_name': 'lewd.dream',
   'name': 'midsummer-s.lewd.dream',
   'type': 'AAAA',
   'content': '8930:8100:1145:141:919:36:114:514',
   'proxiable': True,
   'proxied': False,
   'ttl': 1,
   'locked': False,
   'meta': {'auto_added': False,
    'managed_by_apps': False,
    'managed_by_argo_tunnel': False,
    'source': 'primary'},
   'created_on': '2020-08-24T03:43:46.114514Z',
   'modified_on': '2020-08-24T03:43:46.114514Z'}],
 'success': True,
 'errors': [],
 'messages': [],
 'result_info': {'page': 1,
  'per_page': 20,
  'count': 2,
  'total_count': 2,
  'total_pages': 1}}
@Suncatcher
Copy link

doesn't work, it throws

{"success":false,"errors":[{"code":9106,"message":"Missing X-Auth-Key, X-Auth-Email or Authorization headers"}]}

@PBahner
Copy link

PBahner commented Mar 12, 2024

doesn't work, it throws

{"success":false,"errors":[{"code":9106,"message":"Missing X-Auth-Key, X-Auth-Email or Authorization headers"}]}

@Suncatcher
You need to change 'Authorization' to 'X-Auth-Key' and add 'X-Auth-Email' to the header. This worked for me.

headers = {'X-Auth-Key': auth_key, 'Content-Type':'application/json', 'X-Auth-Email': 'your@email'}

@waddles
Copy link

waddles commented Mar 15, 2024

Doesn't handle pagination

@Suncatcher
Copy link

Suncatcher commented Mar 16, 2024

You need to change 'Authorization' to 'X-Auth-Key' and add 'X-Auth-Email' to the header. This worked for me.

now after your edits it throws

{"success":false,"errors":[{"code":10000,"message":"Authentication error"}]}

Checked twice the zone id, API token and email, they are correct. Any suggestions?

@zarko-a
Copy link

zarko-a commented Apr 16, 2024

I had the same issue and came across this post.

There is a difference between between API Key and API Token, if you have a token that you'd like to use, you need to set the authorization header with bearer token.

I used curl with --header 'Authorization: Bearer < API TOKEN >'

@Suzhou65
Copy link
Author

Suzhou65 commented Apr 19, 2024

Hi, appreciate everyone's response and troubleshooting.

- For safety reason, I will recommend using API Token instead of legacy API Keys.
+ Token with Bearer prefix  more safety, it can modify token’s permissions

Also, according to Cloudflare API Doc, Global API is only available after the account email address is verified.

This gist was only a demonstration of code writing years ago, please move to my GitHub repository Python-Cloudflare-DDNS.

I'll start working on code enhancement ASAP.

@erbanku
Copy link

erbanku commented Jun 1, 2024

This works great for me.

curl --request GET \
--url https://api.cloudflare.com/client/v4/zones/XXXXX/dns_records?name=example.com \
--header 'Content-Type: application/json' \
--header 'X-Auth-Email: [email protected]' \
--header 'X-Auth-Key: XXXXXX' \
> "CF-DNS-Records-Fetch-on-$(date +'%m%d-%H%M%S').json"

@Suncatcher
Copy link

Suncatcher commented Jul 5, 2024

This works great for me.

curl --request GET
--url https://api.cloudflare.com/client/v4/zones/XXXXX/dns_records?name=example.com
--header 'Content-Type: application/json'
--header 'X-Auth-Email: [email protected]'
--header 'X-Auth-Key: XXXXXX' \

"CF-DNS-Records-Fetch-on-$(date +'%m%d-%H%M%S').json"

doesn't work on Windows curl even without backslashes, being one-liner

C:\Users\user\Downloads>curl --request GET --url https://api.cloudflare.com/client/v4/zones/y89f78ds7f8ds7f8s7df8/dns_records?name=url.com --header 'Content-Type: application/json' --header 'X-Auth-Email: [email protected]' --header 'X-Auth-Key: tsdfjdslkfjlksdfjksdjlkfjds'  1>"CF-DNS-Records-Fetch-on-$(date +'d-MS').json"
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   113    0   113    0     0    196      0 --:--:-- --:--:-- --:--:--   196
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:--  0:00:01 --:--:--     0curl: (6) Could not resolve host: application
curl: (3) URL using bad/illegal format or missing URL
curl: (3) URL using bad/illegal format or missing URL

@erbanku
Copy link

erbanku commented Jul 6, 2024

This works great for me.

curl --request GET
--url api.cloudflare.com/client/v4/zones/XXXXX/dns_records?name=example.com
--header 'Content-Type: application/json'
--header 'X-Auth-Email: [email protected]'
--header 'X-Auth-Key: XXXXXX' \

"CF-DNS-Records-Fetch-on-$(date +'%m%d-%H%M%S').json"

doesn't work on Windows curl even without backslashes, being one-liner

C:\Users\user\Downloads>curl --request GET --url https://api.cloudflare.com/client/v4/zones/y89f78ds7f8ds7f8s7df8/dns_records?name=url.com --header 'Content-Type: application/json' --header 'X-Auth-Email: [email protected]' --header 'X-Auth-Key: tsdfjdslkfjlksdfjksdjlkfjds'  1>"CF-DNS-Records-Fetch-on-$(date +'d-MS').json"
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   113    0   113    0     0    196      0 --:--:-- --:--:-- --:--:--   196
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:--  0:00:01 --:--:--     0curl: (6) Could not resolve host: application
curl: (3) URL using bad/illegal format or missing URL
curl: (3) URL using bad/illegal format or missing URL

Please try this, works on Windows PowerShell on my end.

PowerShell

$date = Get-Date -Format "MMdd-HHmmss"; curl --request GET --url https://api.cloudflare.com/client/v4/zones/YOUR_ZONE_ID/dns_records --header "Content-Type: application/json" --header "X-Auth-Email: [email protected]" --header "X-Auth-Key: XXX" --output "CF-DNS-Records-Fetch-on-$date.json"

For Bash on Linux.

Bash

curl --request GET \
--url https://api.cloudflare.com/client/v4/zones/YOUR_ZONE_ID/dns_records \
--header 'Content-Type: application/json' \
--header 'X-Auth-Email: [email protected]' \
--header 'X-Auth-Key: XXX' \
> "CF-DNS-Records-Fetch-on-"$(date +"%m%d-%H%M%S").json

Note

Please use your ZONE_ID, not ACCOUNT_ID.

@erbanku
Copy link

erbanku commented Jul 6, 2024

image

@Suncatcher
Copy link

Suncatcher commented Jul 7, 2024

$date = Get-Date -Format "MMdd-HHmmss"; curl --request GET --url https://api.cloudflare.com/client/v4/zones/YOUR_ZONE_ID/dns_records --header "Content-Type: application/json" --header "X-Auth-Email: [email protected]" --header "X-Auth-Key: XXX" --output "CF-DNS-Records-Fetch-on-$date.json"

this works in PS Core 7.4.2
image

and doesn't work in classic PS 5.0, shipped with Windows
image

Seems like another bit in long list of differences between the two, just to the attention of the folks who will read the thread.

Anyway, thanks a lot @erbanku, I really appreciate your effort in troubleshooting this. Due to your help I received another error and found out I used the wrong token (API token instead of API key), and got a better understand of CF. Bless you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment