python requests with certificate

Python Requests with Certificate

If you are working with Python Requests library and need to make a request to a server that requires SSL/TLS certificate authentication, you may face some challenges. In this blog, we will explore how to use Python Requests with certificate authentication.

What is SSL/TLS Certificate Authentication?

SSL/TLS certificate authentication is a standard way to verify the identity of a server. When a server presents its SSL/TLS certificate, the client can verify the certificate's authenticity using its trusted root certificate authorities. A certificate authority (CA) is a trusted third party that verifies and issues digital certificates.

How to Use Python Requests with Certificate?

To use Python Requests with certificate authentication, you need to provide the cert parameter in the requests.get() or requests.post() method. This parameter accepts a path or list of paths to the client-side certificates.


import requests

cert_path = '/path/to/cert.pem'
url = 'https://example.com'

response = requests.get(url, cert=cert_path)

print(response.content)

In the above code, we are making a GET request to https://example.com with cert.pem as the client-side certificate file. The response content will be printed.

If the server requires a client-side private key, you can provide it using the key parameter in the requests.get() or requests.post() method.


import requests

cert_path = '/path/to/cert.pem'
key_path = '/path/to/key.pem'
url = 'https://example.com'

response = requests.get(url, cert=(cert_path, key_path))

print(response.content)

If you have multiple client-side certificates, you can provide them as a list of paths to the cert parameter.


import requests

cert_paths = ['/path/to/cert1.pem', '/path/to/cert2.pem']
url = 'https://example.com'

response = requests.get(url, cert=cert_paths)

print(response.content)

Conclusion

Python Requests is a powerful library that makes it easy to work with HTTP requests. In this blog, we explored how to use Python Requests with SSL/TLS certificate authentication. We provided examples of providing a single and multiple client-side certificate files and how to provide the client-side private key.