Python Requests Library Certificate Verify Failed
As a developer who has worked with Python, I have come across the error "certificate verify failed" while making requests using the popular Requests library. This error often occurs when trying to access a website with SSL/TLS encryption. In simple words, the SSL certificate presented by the website is not recognized or trusted by the client.
There can be several reasons for this error. Sometimes, the SSL certificate might be expired, self-signed, or not issued by a trusted Certificate Authority (CA). At other times, the client might not have the necessary root certificates installed to verify the SSL certificate.
Solution 1: Disable SSL Verification
One way to bypass this error is to disable SSL verification. However, this is not recommended as it compromises security and leaves the client vulnerable to man-in-the-middle attacks. To disable SSL verification in Python Requests library, we can pass verify=False
as a parameter in the request method.
import requests
response = requests.get('https://example.com', verify=False)
print(response.status_code)
Solution 2: Install Root Certificates
A better solution is to install root certificates on the client's machine to verify SSL certificates. This can be done by updating the ca-certificates
package on Linux or by installing the certifi
package on Windows.
sudo apt-get install ca-certificates
pip install certifi
After installing the root certificates, we can verify SSL certificates using Requests library as usual.
import requests
import certifi
response = requests.get('https://example.com', verify=certifi.where())
print(response.status_code)
Solution 3: Ignore Specific SSL Errors
If we are absolutely sure that the SSL certificate is valid and trusted, but we still get the "certificate verify failed" error, we can ignore specific SSL errors using the ssl.SSLContext
class.
import requests
import ssl
response = requests.get('https://example.com', verify=ssl.create_default_context().load_verify_locations(cafile='/path/to/certificate.pem'))
print(response.status_code)
In the above code, we create a default SSL context and load our custom root certificate. This way, we can bypass any SSL errors that might occur while making requests using the Requests library.