Debug Curl Requests That Fail from Python
In this article
When a curl command works in your terminal but the same request fails inside a Python script, the cause is almost always a difference in environment, headers, or error handling. This guide walks you through a systematic process to isolate and fix those failures, from capturing the exact request to comparing responses.
What You'll Need
- Python 3.6+ installed
- The
requestslibrary (install withpip install requests) - Access to a terminal where the original
curlcommand works - The failing Python script that uses
requests,urllib, orhttp.client
Step-by-Step
- Capture the exact curl command that works. If you have it in your shell history, retrieve it. If not, reconstruct it from your Python code—include the URL, method, headers, body, and any authentication.
- Reproduce the failure in isolation. Create a minimal Python script that only makes the request and prints the status code and body. This removes any interference from your larger application.
- Compare the request headers. Use
curl -vto see the exact headers curl sends. Then in Python, print therequest.headersattribute of your prepared request. Common differences includeUser-Agent,Accept, andContent-Type. - Check for environment differences. Python may be using a different proxy, SSL certificate bundle, or DNS resolver. Set the environment variables
HTTP_PROXY,HTTPS_PROXY, andNO_PROXYto match your shell. For SSL, either setREQUESTS_CA_BUNDLEto the same CA bundle curl uses, or useverify=Falsetemporarily (only for testing). - Inspect the response object fully. In your Python script, print
response.status_code,response.text,response.headers, andresponse.url. A 3xx redirect might be handled differently by curl (which follows by default) and requests (which also follows by default, but you can disable it withallow_redirects=False). - Enable verbose logging. For
requests, uselogging.basicConfig(level=logging.DEBUG)to see the actual bytes sent and received. Forurllib, useurllib.request.urlopen(..., context=ssl._create_unverified_context())to see SSL errors. - Test with the same HTTP version. Curl might use HTTP/2, while requests uses HTTP/1.1 by default. If the server behaves differently, install
httpxand tryhttpx.request(..., http2=True). - Check for cookies and sessions. If the endpoint requires session cookies, use a
requests.Session()object to persist cookies across requests, matching curl's cookie jar behavior. - Compare the exact request body. If you are sending JSON, ensure the encoding and whitespace match. Print the body with
print(request.body). Usejson.dumps()with the same separators as curl's--data. - Test with curl from Python. As a last resort, run the curl command via
subprocess.run()to confirm that the network path is the same. If that works, the issue is in how Python constructs the request.
Common Mistakes
- Ignoring the User-Agent. Some APIs reject requests without a browser-like User-Agent. Curl sends its own; Python's requests sends
python-requests/2.x. Set a custom header. - Not handling redirects. Curl follows redirects by default, but if you use
allow_redirects=Falsein requests, you might get a 3xx instead of the final content. - Forgetting to set Content-Type. When sending JSON, you must set
Content-Type: application/json. Curl's--datasendsapplication/x-www-form-urlencodedby default. - Using the wrong SSL context. Python's default SSL verification might fail if your corporate proxy uses a custom CA. Curl might use a different bundle.
- Mixing up bytes and strings. If you pass a string to
data=in requests, it encodes it as UTF-8. If you pass a dictionary, it form-encodes. Ensure the body type matches what the server expects. - Assuming proxies are not set. Python respects environment variables, but if you set them inside your script, they may override the shell environment. Check with
os.environ.
Tips
- Use
requests.Request()to prepare a request without sending it, then inspectprepared.headersandprepared.body. - Save the curl command with
curl -v ... 2>&1 | tee curl_log.txtto keep a reference. - In Python, use
response.raise_for_status()to catch HTTP errors early, but also print the response text for debugging. - If the server returns a 4xx, check the response body—it often contains a JSON error message that explains the issue.
- For timeouts, set
timeout=(connect, read)in requests to avoid hanging.
Troubleshooting
If the steps above do not resolve the issue, try these additional checks:
- Check DNS resolution. Run
python -c "import socket; print(socket.gethostbyname('example.com'))"and compare withdig example.com. If they differ, your Python environment might be using a different DNS server. - Test with a different library. Switch from
requeststourlliborhttpxto see if the issue is library-specific. - Check for IPv6 issues. If the server only listens on IPv4, Python might try IPv6 first. Set
requests.packages.urllib3.util.connection.HAS_IPV6 = Falseto force IPv4. - Look at the server logs. If you control the server, check its access logs to see if the request even arrives. Compare the request line and headers between curl and Python.
- Use a network sniffer. Tools like Wireshark or tcpdump can show the exact packets sent. This is overkill for most cases, but useful if the server is dropping connections.
Frequently Asked Questions
Why does curl work but Python's requests fail with SSL error?
Python uses its own CA bundle, which may not include your corporate or self-signed certificate. Set the REQUESTS_CA_BUNDLE environment variable to the path of the CA bundle curl uses, or use verify=/path/to/cert.pem.
How do I see the exact request that Python sends?
Prepare the request and print its attributes: req = requests.Request('GET', url, headers=headers) followed by prepared = req.prepare(), then print prepared.url, prepared.headers, and prepared.body.
Why does the server return a 403 Forbidden only from Python?
Often the server is blocking the default Python User-Agent. Set a browser-like User-Agent header, such as Mozilla/5.0.
How do I make Python follow redirects like curl?
requests follows redirects by default. If you are using urllib, you need to handle redirects manually, as urlopen does not follow them by default.
Why does the request hang in Python but not in curl?
Set a timeout in requests: requests.get(url, timeout=10). If it still hangs, the server might be waiting for a header that curl sends but Python does not, like Connection: close.
Can I use curl's output directly in Python?
Yes, you can run curl from Python using subprocess.run() and capture the output. This is a quick workaround, but it is better to fix the underlying difference.