The SSLError: [SSL: CERTIFICATE_VERIFY_FAILED]
is a common error encountered when using Python’s Requests library. This error occurs when the SSL certificate verification fails. Below are several solutions that can help resolve this error, each with its pros and cons.
Solution 1: Update Certificates
Update your system’s certificate bundle to ensure Python can validate SSL certificates properly.
- Locate Python’s certificate file, typically found in your Python installation’s directory.
- Update the certificate bundle using your system’s package manager or by downloading the latest file from a trusted certificate authority.
- Restart your Python application.
Example: Not applicable – This is a system-level solution without specific Python code.
Pros: Updates the system’s trust store; fixes the root cause.
Cons: Might require administrative access; not a quick in-code fix.
Solution 2: Use certifi Package
Utilize the Python ‘certifi’ package which provides Mozilla’s CA Bundle.
- Install the ‘certifi’ package using
pip install certifi
. - Include the ‘certifi’ certificate bundle in your requests.
Code Example:
import requests
import certifi
response = requests.get('https://example.com', verify=certifi.where())
print(response.text)
Pros: Easy to implement; no system-wide changes.
Cons: Adds dependency; might not solve all SSL issues.
Solution 3: Manually Specify Certificate Path
Manually provide the path to a trusted certificate bundle when making requests.
- Obtain a path to a trusted certificate file or bundle.
- Pass that path to the
verify
argument in your request.
Code Example:
import requests
trusted_cert = '/path/to/truststore.pem'
response = requests.get('https://example.com', verify=trusted_cert)
print(response.text)
Pros: Precise control over certificates; good for custom setups.
Cons: Requires manual management; error-prone.
Solution 4: Disable SSL Verification (Not Recommended)
Turn off SSL certificate verification (use with extreme caution).
- Add a
verify=False
parameter to your request.
Code Example:
import requests
warning import warnings # 1.
from requests.packages.urllib3.exceptions import InsecureRequestWarning # 2.
warnings.simplefilter('ignore', InsecureRequestWarning) # 3.
response = requests.get('https://example.com', verify=False) # 4.
print(response.text)
Note: This example also includes suppressing insecure request warnings to prevent cluttering the console output.
Pros: Quick workaround; good for troubleshooting.
Cons: Extremely insecure; exposes to man-in-the-middle attacks.