Specific API endpoint not available via python urllib

Hello! I have an API call that is not working via Python's urllib. The same call is working via curl, and urllib works for other endpoints. I was wondering if anyone has an idea why this call (1) fails, while the others are working (2 curl, 3 other endpoint via urllib). Minimum working example:
#!/usr/bin/python3
import os, json
from urllib.request import Request, urlopen

bearer = MY_API_TOKEN
zone_id = MY_ZONE_ID

try:
request1 = Request(f"https://api.cloudflare.com/client/v4/zones/{zone_id}/cache/cache_reserve",
headers = {"Authorization": f"Bearer {bearer}",
"Content-Type": "application/json"})
response1 = urlopen(request1).read()
print(response1)
except Exception as e:
print(str(e))



request2 = os.popen(f"""curl -s --request GET \
--url https://api.cloudflare.com/client/v4/zones/{zone_id}/cache/cache_reserve \
--header 'Authorization: Bearer {bearer}' \
--header 'Content-Type: application/json'""")

response2 = json.loads(request2.read())
print(response2)

try:
request3 = Request(f"https://api.cloudflare.com/client/v4/zones/{zone_id}",
headers = {"Authorization": f"Bearer {bearer}",
"Content-Type": "application/json"})
response3 = urlopen(request3).read()
print(response3)
except Exception as e:
print(str(e))
#!/usr/bin/python3
import os, json
from urllib.request import Request, urlopen

bearer = MY_API_TOKEN
zone_id = MY_ZONE_ID

try:
request1 = Request(f"https://api.cloudflare.com/client/v4/zones/{zone_id}/cache/cache_reserve",
headers = {"Authorization": f"Bearer {bearer}",
"Content-Type": "application/json"})
response1 = urlopen(request1).read()
print(response1)
except Exception as e:
print(str(e))



request2 = os.popen(f"""curl -s --request GET \
--url https://api.cloudflare.com/client/v4/zones/{zone_id}/cache/cache_reserve \
--header 'Authorization: Bearer {bearer}' \
--header 'Content-Type: application/json'""")

response2 = json.loads(request2.read())
print(response2)

try:
request3 = Request(f"https://api.cloudflare.com/client/v4/zones/{zone_id}",
headers = {"Authorization": f"Bearer {bearer}",
"Content-Type": "application/json"})
response3 = urlopen(request3).read()
print(response3)
except Exception as e:
print(str(e))
Request 1 results in HTTP Error 403: Forbidden
2 Replies
Mackenly
Mackenly4mo ago
Is that all the info you're getting from the exceptions?
Laudian
Laudian4mo ago
Thanks you for the suggestion, you nailed it. After looking at the exception's body, it turns out I'm just stupid. The expected response is all there, I just have to read it from the exceptions body. That's a somewhat annoying design by Urllib.