How to fix Python Cloudflare CloudFlare.exceptions.CloudFlareAPIError: no email and no token defined

Problem:

You want to run a program using the Cloudflare API, e.g. this example code:

#!/usr/bin/env python3
import CloudFlare

cf = CloudFlare.CloudFlare()
zones = cf.zones.get()
for zone in zones:
    zone_id = zone['id']
    zone_name = zone['name']
    print(zone_id, zone_name)

But when trying to run it, you see the following error message:

Traceback (most recent call last):
  File "test-cloudflare-api.py", line 5, in <module>
    zones = cf.zones.get()
  File "/usr/local/lib/python3.8/dist-packages/CloudFlare/cloudflare.py", line 672, in get
    return self._base.call_with_auth('GET', self._parts,
  File "/usr/local/lib/python3.8/dist-packages/CloudFlare/cloudflare.py", line 117, in call_with_auth
    self._AddAuthHeaders(headers, method)
  File "/usr/local/lib/python3.8/dist-packages/CloudFlare/cloudflare.py", line 88, in _AddAuthHeaders
    raise CloudFlareAPIError(0, 'no email and no token defined')
CloudFlare.exceptions.CloudFlareAPIError: no email and no token defined

Solution:

The Cloudflare API is missing the credentials you use to login. The easiest way to call the API with credentials is to initialize CloudFlare.CloudFlare() with the email and token as arguments

cf = CloudFlare.CloudFlare(
    email="[email protected]",
    token="Oochee3_aucho0aiTahc8caVuak6Que_N_Aegi9o"
)

Note that you can’t do all operations with all tokens and if you perform an operation that is not possible with your token, you’ll see an error message like CloudFlare.exceptions.CloudFlareAPIError: Invalid request headers