python requests with cert and key

Python Requests with Cert and Key

If you're working with APIs that require SSL/TLS client authentication, you will need to use a client certificate and private key to authenticate your requests. The good news is that the Python Requests library has built-in support for client-side certificates.

Using Certificates with Requests

To use client certificates with Requests, you need to pass the path to the certificate file and private key file as a tuple to the cert parameter when making a request:


import requests

cert = ('/path/to/cert.pem', '/path/to/key.pem')
response = requests.get('https://api.example.com', cert=cert)

print(response.text)
    

In this example, we are passing the paths to the certificate file and private key file as a tuple to the cert parameter. This will tell Requests to use these files for SSL/TLS client authentication when making the request.

Using Certificates with Requests and a Password

If your private key is password-protected, you can pass the password as a string to the cert parameter:


import requests

cert = ('/path/to/cert.pem', '/path/to/key.pem', 'password')
response = requests.get('https://api.example.com', cert=cert)

print(response.text)
    

In this example, we are passing the paths to the certificate file and private key file as well as the password as a tuple to the cert parameter. This will tell Requests to use these files and password for SSL/TLS client authentication when making the request.

Using Certificates with Requests and a CA Bundle

If your certificate was issued by a Certificate Authority (CA), you may also need to specify the path to the CA bundle file using the verify parameter:


import requests

cert = ('/path/to/cert.pem', '/path/to/key.pem', 'password')
response = requests.get('https://api.example.com', cert=cert, verify='/path/to/ca.pem')

print(response.text)
    

In this example, we are passing the paths to the certificate file, private key file, and password as well as the path to the CA bundle file to the cert and verify parameters. This will tell Requests to use these files for SSL/TLS client authentication and verify the server's certificate against the CA bundle when making the request.