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.

Introduction & Quick Summary
An HTTPS call that worked on a laptop fails on a server, a container, or a colleague's Mac:
>>> 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:
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:
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:
| Variable | Consumed by | Effect |
|---|---|---|
verify= argument | requests, httpx | per-request override |
REQUESTS_CA_BUNDLE | requests | bundle path for all sessions |
CURL_CA_BUNDLE | requests fallback | same, shared with curl wrappers |
SSL_CERT_FILE | ssl, urllib, pip | file path appended to the default store |
SSL_CERT_DIR | ssl, urllib | directory 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.
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)
PYThe 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 tail | Cause | Fix |
|---|---|---|
unable to get local issuer certificate | bundle lacks the intermediate or root | use a current bundle, or the corporate CA |
self-signed certificate in certificate chain | TLS inspection by a proxy | add the proxy's root to the bundle |
certificate has expired | stale bundle or server cert | update certifi, renew the server cert |
hostname mismatch | certificate CN/SAN differs | correct the URL or the certificate |
wrong version number | HTTPS to an HTTP port | fix the scheme or port |
EOF occurred in violation of protocol | proxy or TLS version mismatch | check proxy, minimum TLS version |
| Client | Default trust source | Override |
|---|---|---|
requests | certifi.where() | verify=, REQUESTS_CA_BUNDLE |
httpx | certifi | verify= |
urllib.request | ssl.create_default_context() | context=, SSL_CERT_FILE |
aiohttp | certifi via ssl connector | ssl.create_default_context(cafile=...) |
boto3 | botocore bundle | AWS_CA_BUNDLE |
pip | certifi | --cert, PIP_CERT |
| Fix | Security | When appropriate |
|---|---|---|
update certifi | unchanged | expired root in an old bundle |
| add a corporate root | unchanged for real hosts | TLS inspection you must traverse |
| pin a server certificate | stronger | internal service with a known cert |
verify=False | removed | never in production |
disable via urllib3.disable_warnings | removed | never |
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:
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:
# 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:
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 -10A 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.
# python.org macOS
ls "/Applications/Python 3."*/Install\ Certificates.command
# conda
conda install -c conda-forge certifi ca-certificatesMixing 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:
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 reliableFor 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:
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 callNever 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=Falseas the fix. It removes authentication for every request in that session and hides the real problem from logs.- Pointing
SSL_CERT_FILEat 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
ssluses OpenSSL paths, not the macOS Keychain or the Windows certificate store, andrequestsusescertifi. - 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 nextpip installoverwrites them; append a separate bundle or use the environment variable. - Ignoring the proxy variable.
HTTPS_PROXYwith an intercepting proxy produces exactly theself-signed certificate in certificate chainerror, and the CA must be added, not the proxy removed.
Official documentation: Python ssl module and requests: SSL certificate verification.
Official references
primary documentationThe Python documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython Typer Rich Integration and Progress Bars
python typer rich integration and progress bars: Learn to integrate Rich progress bars into Typer CLI applications, covering track, Progress, dynamic.
Python Wildcard Pattern Matching with fnmatch and glob
Learn Python's wildcard pattern matching with fnmatch, glob, and pathlib to filter strings and file paths using *, ?, and character sets.
Python 3.14 PEP 649: NameError from lazy annotations
Annotations are no longer strings. A NAME only imported under TYPE_CHECKING now raises when FastAPI or Pydantic reads the signature.
asyncpg DuplicatePreparedStatement on PgBouncer and Supabase
asyncpg caches prepared statements per connection while a transaction pooler rotates connections underneath it. The cache setting, pool sizing and retry.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.