How to fix Python Cloudflare CloudFlare.exceptions.CloudFlareAPIError: 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({
    "email": "[email protected]",
    "token": "Oochee3_aucho0aiTahc8caVuak6Que_N_Aegi9o" 
})
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 "run.py", line 8, in 
    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 90, in _AddAuthHeaders
    raise CloudFlareAPIError(0, 'no token defined')
CloudFlare.exceptions.CloudFlareAPIError: no token defined

Solution:

You are using the wrong syntax to give arguments to CloudFlare.CloudFlare(), use email=… and token=… arguments directly instead of using a dict!

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