Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python: SSLCertVerificationError certificate verify failed

Python could not build a trusted chain to the server. Point OpenSSL at a current CA bundle, fix the missing intermediate, and keep verification on.

~5 min readPython
#python#ssl#requests#certificates
Python SSL handshake diagram with a broken certificate chain and a CA bundle crate beside it

Introduction & Quick Summary

An HTTPS call that worked on a laptop fails on a server, a container, or a colleague's Mac:

python
>>> requests.get("https://api.example.com/health") requests.exceptions.SSLError: HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded with url: /health (Caused by SSLError(SSLCertVerificationError( 1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1016)')))

Quick answer: Python could not build a trusted chain from the server's certificate to a root CA it knows. The fix is to give OpenSSL the right bundle, not to switch verification off:

python
import certifi, requests r = requests.get("https://api.example.com/health", verify=certifi.where(), timeout=10)

or, process-wide, before any client is constructed:

export SSL_CERT_FILE="$(python -c 'import certifi; print(certifi.where())')" export REQUESTS_CA_BUNDLE="$SSL_CERT_FILE"

Three variants of the message point at different causes. unable to get local issuer certificate means the chain is incomplete or the root is unknown. self-signed certificate in certificate chain means a proxy or an internal CA is intercepting. certificate has expired means the bundle or the server certificate is stale. Read the last line of the exception, then check the bundle Python is actually using.

Core Mechanics, Signatures & Reproducible Setup

Python's ssl module wraps OpenSSL. A client context created with ssl.create_default_context() calls load_default_certs(), which reads the system store, and Python enhances that with the certifi bundle in some distributions. requests and httpx ship their own default: certifi.where().

Inspect what the interpreter sees:

python
import ssl, certifi, sys print(sys.version) print(ssl.OPENSSL_VERSION) print(ssl.get_default_verify_paths()) # cafile, capath, openssl_cafile_env, ... print(certifi.where())

Values that change the outcome, in order of precedence:

VariableConsumed byEffect
verify= argumentrequests, httpxper-request override
REQUESTS_CA_BUNDLErequestsbundle path for all sessions
CURL_CA_BUNDLErequests fallbacksame, shared with curl wrappers
SSL_CERT_FILEssl, urllib, pipfile path appended to the default store
SSL_CERT_DIRssl, urllibdirectory of hashed certificates

A reproduction against a server with a private chain, without needing one: point a client at a host whose root is not in the bundle by using a local self-signed certificate.

bash
openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 2 -subj "/CN=localhost" python -m http.server 8443 --bind 127.0.0.1 --directory . & # plain HTTP, for contrast python - <<'PY' import ssl, urllib.request ctx = ssl.create_default_context() try: urllib.request.urlopen("https://127.0.0.1:8443/", context=ctx, timeout=3) except Exception as e: print(type(e).__name__, e) PY

The error names the missing trust anchor. Adding cafile="cert.pem" to create_default_context makes the same request succeed, which is exactly the mechanism a corporate proxy requires.

Key Comparison Table

Message tailCauseFix
unable to get local issuer certificatebundle lacks the intermediate or rootuse a current bundle, or the corporate CA
self-signed certificate in certificate chainTLS inspection by a proxyadd the proxy's root to the bundle
certificate has expiredstale bundle or server certupdate certifi, renew the server cert
hostname mismatchcertificate CN/SAN differscorrect the URL or the certificate
wrong version numberHTTPS to an HTTP portfix the scheme or port
EOF occurred in violation of protocolproxy or TLS version mismatchcheck proxy, minimum TLS version
ClientDefault trust sourceOverride
requestscertifi.where()verify=, REQUESTS_CA_BUNDLE
httpxcertifiverify=
urllib.requestssl.create_default_context()context=, SSL_CERT_FILE
aiohttpcertifi via ssl connectorssl.create_default_context(cafile=...)
boto3botocore bundleAWS_CA_BUNDLE
pipcertifi--cert, PIP_CERT
FixSecurityWhen appropriate
update certifiunchangedexpired root in an old bundle
add a corporate rootunchanged for real hostsTLS inspection you must traverse
pin a server certificatestrongerinternal service with a known cert
verify=Falseremovednever in production
disable via urllib3.disable_warningsremovednever

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. The bundle is old, not wrong

Root CAs expire. A container built a year ago can hold a bundle with roots that have since been distrusted:

bash
python -c "import certifi; print(certifi.where())" pip install --upgrade certifi python -c "import certifi,ssl; print(len(ssl.create_default_context(cafile=certifi.where()).get_ca_certs()))"

Pinning certifi==2024.2.2 in a lockfile is fine; never pinning it and never rebuilding the image is not.

2. Corporate proxy and TLS inspection

An intercepting proxy presents its own certificate, signed by an internal root. The browser trusts it because the OS store has it; Python does not, because certifi is a separate list:

bash
# export the internal root once, in PEM form security find-certificate -a -p /Library/Keychains/System.keychain > corp-roots.pem # macOS # combine: system roots + corporate roots python - <<'PY' import certifi with open("bundle.pem", "wb") as out: out.write(open(certifi.where(), "rb").read()) out.write(open("corp-roots.pem", "rb").read()) PY export REQUESTS_CA_BUNDLE="$PWD/bundle.pem"

Concatenating PEM files is valid; a single certificate file that replaces the bundle is not, and produces unable to get local issuer certificate for every other host.

3. Missing intermediate on the server

If openssl s_client shows the leaf certificate only, the server is misconfigured and every strict client fails, not just Python:

bash
openssl s_client -connect api.example.com:443 -servername api.example.com -showcerts </dev/null 2>/dev/null | \ grep -E "^ *[0-9]+ s:|^ *i:" | head -10

A chain with one s: (subject) and no i: (issuer) beyond the leaf means the intermediate is missing. Fix it on the server; a client-side workaround only hides a broken TLS configuration from everyone else too.

4. Platform-specific interpreters

The python.org macOS installer ships without a populated trust store by default; its Install Certificates.command links the bundled certifi into place. Homebrew Python uses its own OpenSSL and usually works with certifi from the start. Conda has a separate certifi package.

bash
# python.org macOS ls "/Applications/Python 3."*/Install\ Certificates.command # conda conda install -c conda-forge certifi ca-certificates

Mixing interpreters in the same shell (system python3, a pyenv shim, and a venv) is the most common reason "it works in one terminal".

5. Sessions, clients and long-lived processes

Setting the environment variable after a client or session exists has no effect on objects already built:

python
import os, requests os.environ["REQUESTS_CA_BUNDLE"] = "/etc/ssl/certs/corp-bundle.pem" # too late if imported earlier session = requests.Session() session.verify = "/etc/ssl/certs/corp-bundle.pem" # explicit and reliable

For httpx, the same idea with httpx.Client(verify=...). For async clients, build the SSLContext once and pass it in, rather than per request.

6. When verification must be disabled, isolate it

There are cases — a lab device with a self-signed certificate you cannot replace — where disabling verification is the only available option. Put it in the narrowest scope, and make it visible:

python
import requests, urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) DEVICE = "https://192.0.2.10/api" resp = requests.get(DEVICE, verify=False, timeout=5) # only this host, only this call

Never set verify=False in a shared session or a library default; the flag then leaks to every request the process makes.

The curl tool reproduces the same TLS handshake outside Python, which separates a bundle problem from a client bug, and the regular expression tester pulls the failing host out of a long traceback.

Common Compilation/Runtime Mistakes & Version Gotchas

  • verify=False as the fix. It removes authentication for every request in that session and hides the real problem from logs.
  • Pointing SSL_CERT_FILE at a single certificate. That file becomes the whole bundle; other hosts then fail with the same message.
  • Assuming the OS store is used. Python's ssl uses OpenSSL paths, not the macOS Keychain or the Windows certificate store, and requests uses certifi.
  • Updating only the app container. A build stage or a different base image can still carry the old bundle.
  • Confusing hostname mismatch with chain failure. They are different checks and different fixes; read the full message.
  • Editing certifi's package files. The next pip install overwrites them; append a separate bundle or use the environment variable.
  • Ignoring the proxy variable. HTTPS_PROXY with an intercepting proxy produces exactly the self-signed certificate in certificate chain error, and the CA must be added, not the proxy removed.

Official documentation: Python ssl module and requests: SSL certificate verification.

Official references

primary documentation

The Python documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.