How to Fix Python Requests SSL Certificate Verify Failed Error
In this tutorial, you'll learn about How to Fix Python Requests SSL Certificate Verify Failed Error. We cover key concepts, practical examples, and best practices.
Python Requests raises SSLError: Certificate verify failed when it cannot validate the SSL certificate of the target server.
The Wrong Way
import requests
response = requests.get("https://self-signed.example.com")
print(response.text)
This produces:
requests.exceptions.SSLError: HTTPSConnectionPool(host='self-signed.example.com', port=443):
Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1,
'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate (_ssl.c:1000)')))
The Right Way
Use verify=False only as a last resort, and add proper certificate handling:
import requests
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
response = requests.get("https://self-signed.example.com", verify=False)
print(response.status_code)
Output:
200
Step-by-Step Fix
1. Update CA certificates
pip install --upgrade certifi
2. Use a custom CA bundle
import requests
response = requests.get(
"https://internal.example.com",
verify="/path/to/custom-ca-bundle.crt"
)
3. Use certifi to find the system CA bundle
import certifi
import requests
response = requests.get(
"https://example.com",
verify=certifi.where()
)
4. Set REQUESTS_CA_BUNDLE environment variable
export REQUESTS_CA_BUNDLE=/path/to/ca-bundle.crt
python3 script.py
5. Create a custom SSL context
import ssl
import requests
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
session = requests.Session()
session.verify = False
Prevention Tips
- Never disable certificate verification in production code.
- Keep CA certificates updated with
pip install --upgrade certifi. - Use proper SSL certificates from trusted authorities.
- For internal services, add self-signed certificates to the trust store.
- Use
verify=REQUESTS_CA_BUNDLEfrom environment configuration.
Common Mistakes with requests ssl
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro