403 API Call Adding DNS record.

I have an API token created with permissions to edit zone, zone settings, ssl & certs, and dns firewall. when i try and post to the dns_records api and create a record it's failing with a 403 forbidden for url.

i verified i have my token being used and that my zone ID is correct. any ideas?

requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://api.cloudflare.com/client/v4/zones/myzonehere/dns_records

my code:

# Function to add DNS record for a subdomain
def add_dns_a_record(subdomain: str, ip_address: str) -> str:
    url = f"https://api.cloudflare.com/client/v4/zones/{settings.CLOUDFLARE_ZONE_ID}/dns_records"

    headers = {
        'Authorization': f'Bearer {settings.CLOUDFLARE_API_TOKEN}',
        'Content-Type': 'application/json'
    }

    data = {
        "type": "A",
        "name": subdomain,
        "content": ip_address,
        "ttl": 3600,
        "proxied": True
    }

    try:
        # Make the API request to create the DNS record
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()

        # Parse the API response
        result = response.json()

        # Return the ID of the newly created DNS record
        return result['result']['id']

    except requests.exceptions.HTTPError as e:
        print(f"HTTP error occurred: {e.response.status_code} - {e.response.text}")
        raise

    except Exception as e:
        print(f"An error occurred: {str(e)}")
        raise
Was this page helpful?