python requests x509 certificate

Python Requests X509 Certificate

If you are working with secure websites and APIs, you may need to use an X509 certificate to authenticate your requests. Python Requests is a popular library for making HTTP requests, and it provides built-in support for working with X509 certificates.

Using an X509 Certificate with Requests

To use an X509 certificate with Requests, you need to create a session and pass in the path to your certificate file and key file:


import requests

session = requests.Session()
session.cert = ('/path/to/cert.pem', '/path/to/key.pem')

response = session.get('https://example.com/api')

The cert attribute of the session object is a tuple containing the path to the certificate file and the path to the key file.

You can also pass in a tuple of client-side certificates, which can be useful if the server requires a chain of certificates to validate your identity:


import requests

cert_files = ('/path/to/cert1.pem', '/path/to/cert2.pem')
key_file = '/path/to/key.pem'

session = requests.Session()
session.cert = (cert_files, key_file)

response = session.get('https://example.com/api')

Verifying Server Certificates

When making requests over HTTPS, Python Requests verifies the server's SSL certificate by default. If the certificate cannot be verified, Requests will raise a requests.exceptions.SSLError. You can disable this behavior by setting verify=False:


import requests

session = requests.Session()
session.verify = False

response = session.get('https://example.com/api')

However, it's generally a bad idea to disable certificate verification, as it opens you up to vulnerability to man-in-the-middle attacks. Instead, you should include the server's SSL certificate in your certificate store:


import requests

session = requests.Session()
session.verify = '/path/to/ca-bundle.crt'

response = session.get('https://example.com/api')

The verify attribute of the session object is set to the path of a CA bundle file that contains the server's SSL certificate. This file should be in PEM format.