Bearer auth doesn't work with python requests

Hi,

I’m trying to use the purge_cache endpoint from a python app. I have created an API Token for that purpose. When trying with curl everything works fine:

curl -X POST "https://api.cloudflare.com/client/v4/zones/<zone_id>/purge_cache" \
     -H "Authorization: Bearer <token>" \
     -H "Content-Type: application/json" \
     --data '{"purge_everything":true}'

But when I try with requests (python3) then I get this error:

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

This is my python code:

import json
import requests

api_url = 'https://api.cloudflare.com/client/v4/zones/{0}/purge_cache'.format(CF_ZONE_ID)
headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer {0}'.format(CF_TOKEN)
}
data = {
    'purge_everything': 'true'
}

response = requests.post(url=api_url, headers=headers, json=data)

print(json.loads(response.content.decode('utf-8')))

Print the headers before you do the POST, maybe your variable injection isn’t working correctly or is injecting an empty string for CF_TOKEN.

Also, in your data, the true should be a python boolean, not a string.

data = {
    'purge_everything': True
}
2 Likes

Thanks, good catch!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.