python requests client certificate

Python Requests Client Certificate

If you want to use client certificates with Python Requests library, you can do it by passing a verify argument to the requests.get() or requests.post() method. The verify argument is used to specify the path to the trusted CA bundle file or the path to the client certificate and private key files:


import requests

# Path to the client certificate and private key files
client_cert = ('/path/to/client/cert.pem', '/path/to/client/key.pem')

# Path to the CA bundle file
ca_bundle = '/path/to/ca/bundle.pem'

response = requests.get('https://example.com', cert=client_cert, verify=ca_bundle)

In the example above, we pass the path to the client certificate and private key files using a tuple (client_cert) and the path to the CA bundle file using a string (ca_bundle). We then make a GET request to https://example.com and pass the cert and verify arguments to the method.

Using a Dictionary for Multiple Certificates

If you have multiple client certificates and private keys, you can use a dictionary to pass them to the cert argument:


import requests

# Dictionary of client certificates and private keys
client_certs = {
    'client1': ('/path/to/client1/cert.pem', '/path/to/client1/key.pem'),
    'client2': ('/path/to/client2/cert.pem', '/path/to/client2/key.pem')
}

# Path to the CA bundle file
ca_bundle = '/path/to/ca/bundle.pem'

response = requests.get('https://example.com', cert=client_certs['client1'], verify=ca_bundle)

In the example above, we define a dictionary (client_certs) that maps client names to tuples of client certificate and private key files. We then make a GET request to https://example.com and pass the cert argument with the client name ('client1') to use the corresponding certificate and private key.

Using Certificates from Environment Variables

If you want to use client certificates stored in environment variables, you can do it by reading the variables and passing them to the cert argument:


import requests
import os

# Read client certificate and private key from environment variables
client_cert = (os.environ['CLIENT_CERT'], os.environ['CLIENT_KEY'])

# Read CA bundle file from environment variable
ca_bundle = os.environ['CA_BUNDLE']

response = requests.get('https://example.com', cert=client_cert, verify=ca_bundle)

In the example above, we read the client certificate and private key from the CLIENT_CERT and CLIENT_KEY environment variables using the os.environ dictionary. We then read the CA bundle file from the CA_BUNDLE environment variable. Finally, we make a GET request to https://example.com and pass the cert and verify arguments with the corresponding values.