---
title: "How to Fix Python Requests SSLError: Certificate Errors"
description: "Python Requests SSLError means the TLS check failed before your request left. Read the reason in the message, then fix the CA bundle, proxy URL or certificate."
url: https://proxynet.io/blog/python-requests-sslerror
date: 2026-11-30
author: "Acar Diveroli"
category: "Tutorial"
lang: en
---

# How to Fix Python Requests SSLError: Certificate Errors

A script that has called the same API every night for months stops on the first line of the log: `requests.exceptions.SSLError: HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded with url: /v1/orders (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1032)')))`. Nothing in the code changed. What changed is somewhere else: the office network, a new Docker image, a Python upgrade or the server's certificate.

This guide shows how to read that long line, maps each reason text to its cause with errors we reproduced on badssl.com and on local test servers, gives a small script that finds the cause on your own machine, and fixes the cases that come up most: an outdated or missing CA bundle, a company proxy that inspects TLS, `REQUESTS_CA_BUNDLE` overriding your code, a proxy URL written with `https://`, and client certificates.

> **Note: Short answer**
>
> Requests raises `SSLError` when the TLS handshake fails, before any HTTP is sent. The text after `certificate verify failed:` names the cause. `unable to get local issuer certificate` or `self-signed certificate in certificate chain`: the issuing CA is not in the bundle Requests reads, so update certifi or pass `verify="bundle.pem"` with your company root added to the certifi roots. `Hostname mismatch` or `certificate has expired`: the server's certificate is wrong, so fix the URL or the server. `WRONG_VERSION_NUMBER`: you spoke TLS to a plain HTTP port, often a proxy URL that starts with `https://` instead of `http://`. `verify=False` only proves the cause; it is never the fix.

## What does requests.exceptions.SSLError mean?

It means the TLS handshake under your HTTPS request failed, so the server never saw the request. Requests passes the job to urllib3, urllib3 uses Python's `ssl` module, and that module uses OpenSSL. Each layer wraps the error of the one below, which is why the line is so long.

Read it from the inside out. `HTTPSConnectionPool(host=..., port=...)` is the address urllib3 tried. `Max retries exceeded` is part of the template and does not mean anything was retried: with Requests' defaults the handshake ran once. `SSLCertVerificationError` means the certificate check failed, while a plain `SSLError(SSLError(1, ...))` means the handshake broke for another reason, such as a protocol mismatch. The text after `certificate verify failed:` is the part to search for.

`requests.exceptions.SSLError` is a subclass of `requests.exceptions.ConnectionError`. If your code catches `ConnectionError` first, certificate failures end up in the same branch as network outages, and the log never shows which one happened.

## How does Requests check a certificate?

1. **It picks a CA bundle.** By default that is the `cacert.pem` file of the certifi package, Mozilla's list of trusted roots. A `verify=` path, or the `REQUESTS_CA_BUNDLE` or `CURL_CA_BUNDLE` environment variable, replaces it.
2. **It builds the chain.** The server sends its certificate and usually one or more intermediate certificates; each must be signed by the next, up to a root in the bundle.
3. **It checks the name.** The host in your URL must appear in the certificate's subject alternative names; for an IP address, the IP must be listed.
4. **It checks the dates.** The current time on your machine must fall between the certificate's start and end dates.
5. **It applies strict rules on Python 3.13+.** Python 3.13 added `VERIFY_X509_STRICT` and `VERIFY_X509_PARTIAL_CHAIN` to its default context, and urllib3 does the same on 3.13 since version 2.4.0, so certificates that break RFC 5280 now fail even when the chain is complete.

Requests does not read the Windows or macOS certificate store, and it ignores `SSL_CERT_FILE`. In our test, setting `SSL_CERT_FILE` to our test root made `urllib.request` succeed while Requests still failed. That is the main reason a site opens in the browser but not in your script.

## What does each SSLError message mean?

We ran Python 3.13.17 with Requests 2.34.2, urllib3 2.6.3 and OpenSSL 3.5.9 on Windows 11. We reproduced the rows on badssl.com test hosts (expired, self-signed, untrusted root, incomplete chain, wrong host, TLS 1.0) and on local servers on 127.0.0.1 with a test CA we created.

| Text in the error | What it means | First fix |
|---|---|---|
| `certificate has expired` | The end date has passed | Server renews; check your clock |
| `certificate is not yet valid` | The start date is in the future | Fix your system clock |
| `self-signed certificate` | The server signed its own certificate | Trust that cert for your own host only |
| `self-signed certificate in certificate chain` | The chain ends at a root you lack | Add that root to your bundle |
| `unable to get local issuer certificate` | An issuer is missing from your bundle | Update certifi or add the CA |
| `Hostname mismatch` | The name is not in the certificate | Use the right host name |
| `IP address mismatch` | You called an IP the cert does not list | Call the host name |
| `Basic Constraints of CA cert not marked critical` | Python 3.13 strict rules reject the CA | Ask the CA owner to reissue |
| `Missing Authority Key Identifier` | Same strict rules, on the leaf | Reissue the certificate |
| `WRONG_VERSION_NUMBER` | TLS sent to a port that speaks plain HTTP | Use `http://` for that port |
| `SSLV3_ALERT_HANDSHAKE_FAILURE` | No shared protocol or cipher | The server needs TLS 1.2 or later |
| `[SSL] PEM lib` | Your client certificate file is wrong | Pass the certificate and key |

Two badssl.com hosts that only speak TLS 1.0 and TLS 1.1 both failed with `SSLV3_ALERT_HANDSHAKE_FAILURE`, because urllib3 has used TLS 1.2 as its minimum version since 2.0. That is a server that needs updating, not a certificate problem on your side.

## How do you find the cause on your machine?

Run a check that reads the same bundle as Requests and prints OpenSSL's verify code, outside of your application. The script below shows the Python, OpenSSL, Requests and certifi versions, the environment variables that change Requests' behaviour, and the result of a handshake with each host you pass:

```python
"""Show what Requests trusts on this machine and why a TLS handshake fails."""
import argparse
import os
import socket
import ssl
import sys
import urllib.request

import certifi
import requests

def show_setup() -> None:
    print("Python  ", sys.version.split()[0], "|", ssl.OPENSSL_VERSION)
    print("requests", requests.__version__, "| certifi", certifi.__version__)
    print("bundle  ", certifi.where())
    for name in ("REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"):
        print(f"{name:<18}", os.environ.get(name, "-"))
    print("proxies ", urllib.request.getproxies() or "-")

def check(host: str, port: int, cafile: str) -> None:
    # Same checks as Requests: certifi bundle (or your file), hostname, dates
    ctx = ssl.create_default_context(cafile=cafile)
    try:
        with socket.create_connection((host, port), timeout=10) as sock:
            with ctx.wrap_socket(sock, server_hostname=host) as tls:
                cert = tls.getpeercert()
                print(f"{host}:{port} OK, {tls.version()}, valid until {cert['notAfter']}")
    except ssl.SSLCertVerificationError as err:
        print(f"{host}:{port} certificate problem {err.verify_code}: {err.verify_message}")
    except ssl.SSLError as err:
        print(f"{host}:{port} TLS problem: {err.reason}")
    except OSError as err:
        print(f"{host}:{port} network problem: {err}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("targets", nargs="*", default=["example.com"])
    parser.add_argument("--cafile", default=certifi.where())
    args = parser.parse_args()
    show_setup()
    for target in args.targets:
        name, _, port = target.partition(":")
        check(name, int(port or 443), args.cafile)
```

Save it as `diagnose_tls.py` and run `python diagnose_tls.py example.com untrusted-root.badssl.com incomplete-chain.badssl.com`. Part of our output:

```text
requests 2.34.2 | certifi 2025.11.12
REQUESTS_CA_BUNDLE -
example.com:443 OK, TLSv1.3, valid until Feb 22 23:53:08 2027 GMT
untrusted-root.badssl.com:443 certificate problem 19: self-signed certificate in certificate chain
incomplete-chain.badssl.com:443 certificate problem 20: unable to get local issuer certificate
```

`verify_code` and `verify_message` are attributes of Python's [ssl.SSLCertVerificationError](https://docs.python.org/3/library/ssl.html#ssl.SSLCertVerificationError), and the numbers are OpenSSL's: 10 for expired, 19 for an untrusted root in the chain, 20 for a missing issuer, 62 for a host name mismatch, 64 for an IP mismatch. If the script connects without a problem while your application fails, compare the bundle path and the environment variables in the first lines: the application is reading a different list. The script connects directly, so if your traffic normally goes through a proxy, run it on the same network as the application.

## How do you fix an outdated or missing CA bundle?

Update certifi first, because Requests trusts only the roots in that package. Run `python -m pip install --upgrade certifi` in the same environment as your script, then check the result with `python -m certifi`, which prints the bundle path. The latest release on PyPI was 2026.11.20 when we checked; our test machine still had 2025.11.12, which shows how easily an old virtual environment falls behind. The Requests documentation itself recommends upgrading certifi often.

On macOS with Python from the python.org installer, the interpreter has no root certificates until you run `Install Certificates.command` once from the `/Applications/Python 3.x/` folder, as the [Python on macOS documentation](https://docs.python.org/3/using/mac.html) describes.

If the server uses a private CA, an internal one or a new public root that certifi does not have yet, pass the file to `verify`:

```python
import requests

# One request
r = requests.get("https://intranet.example.test/health", verify="certs/internal-root.pem", timeout=10)

# Every request in a session
session = requests.Session()
session.verify = "certs/internal-root.pem"
```

The file replaces the certifi bundle, it is not added to it. A file that holds only the internal root makes every public site fail. When the same script also calls public APIs, combine the two files:

```bash
cat "$(python -m certifi)" certs/internal-root.pem > certs/ca-bundle-plus-internal.pem
```

The file must be PEM, the text format that starts with `-----BEGIN CERTIFICATE-----`. If you received a binary `.der` or `.cer` file, convert it with `openssl x509 -inform der -in root.der -out root.pem`. A directory also works for `verify`, but only after OpenSSL's `c_rehash` tool has processed it.

The other route is the operating system's store. The `truststore` package (Python 3.10 or later) makes Requests verify through the Windows, macOS or Linux store after one call, `truststore.inject_into_ssl()`, at the start of your script; its [documentation](https://truststore.readthedocs.io/en/latest/) reserves this call for applications and scripts, not libraries. With truststore on Windows, our error text came from Windows itself, in the system's display language.

The system-store side for npm, Git and curl is covered in [Unable to Get Local Issuer Certificate](/blog/unable-to-get-local-issuer-certificate).

## How do you fix SSLError behind a company proxy or a debugging tool?

Add the root certificate of the tool that re-signs the traffic, combined with the certifi roots. Company web gateways, antivirus products with HTTPS scanning, and debugging proxies such as mitmproxy, Charles and Burp Suite open the encrypted connection and present a new certificate for each site, signed by their own root. The browser trusts that root because IT installed it in the system store; Requests, reading certifi, does not.

We ran a local proxy on 127.0.0.1 that re-signs traffic the way a company gateway does, with a test root called Example Corp Root CA. A request to `https://api.ipify.org` through it failed with `unable to get local issuer certificate`. With `verify` pointing at the combined file (certifi plus our root), it returned `200`. With the test root alone, it also worked, but only through the proxy: the same request without the proxy failed. Laptops move between office, home and VPN, so use the combined file.

For mitmproxy, the root is `~/.mitmproxy/mitmproxy-ca-cert.pem`, created on first start. For a company gateway, ask IT for the root certificate in PEM format; never take one from an unofficial source, because a root you trust can sign for any site. Setting up such a tool, including the certificate step, is explained in [What Is a MITM Proxy?](/blog/mitm-proxy)

Python 3.13 adds a newer case: an older gateway or debugging CA may fail with `Basic Constraints of CA cert not marked critical` even though you added the right root. The certificate breaks RFC 5280, and the strict flag now rejects it. The Python documentation shows how to switch the flag off but does not recommend it; the lasting fix is a reissued CA certificate from whoever runs the gateway.

## Why does REQUESTS_CA_BUNDLE override Session.verify?

Because Requests reads the environment for every request whose own `verify` is left at the default, and the environment value then wins over the session value. The logic sits in `Session.merge_environment_settings`: if the request's `verify` is `True` or unset, `REQUESTS_CA_BUNDLE` or `CURL_CA_BUNDLE` takes its place, and only after that is the session's `verify` merged in.

In our test, `REQUESTS_CA_BUNDLE` pointed at our test root alone and the session had `session.verify` set to the combined file. A request to `api.ipify.org` failed with `unable to get local issuer certificate`. Passing `verify=` on the request itself returned `200`, and so did `session.trust_env = False`. When a script behaves differently on two machines, print `os.environ.get("REQUESTS_CA_BUNDLE")` first; CI systems and shell profiles often set it.

`trust_env = False` also turns off `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` and `.netrc`, so set the proxy on the session yourself when you use it.

## What causes WRONG_VERSION_NUMBER with a proxy?

Writing the proxy URL with `https://` when the proxy speaks plain HTTP. The proxy scheme describes the connection from your script to the proxy, not the site you visit. An HTTP proxy receives `CONNECT api.ipify.org:443`, opens a tunnel and passes the encrypted bytes through, so an `https://` site still uses an `http://` proxy URL:

```python
proxies = {
    "http": "http://user:pass@pr.proxynet.io:8000",
    "https": "http://user:pass@pr.proxynet.io:8000",  # http:// here as well
}
```

With `https://127.0.0.1:47606` pointing at our local HTTP proxy, the error was not an `SSLError` but a `ProxyError`, with a hint from urllib3: `Your proxy appears to only use HTTP and not HTTPS, try changing your proxy URL to be HTTP`, followed by `[SSL: WRONG_VERSION_NUMBER] wrong version number`. The same error without a proxy means the URL has `https://` and a port that serves plain HTTP. The reverse, `http://` against a TLS port, showed up as a `ConnectionError` with the connection reset, not as an `SSLError`. All proxy settings, including SOCKS5 and environment variables, are in [How to Use a Proxy With Python Requests](/blog/python-requests-proxy).

A tunnelling proxy does not touch certificates: through our plain tunnel, the site's own certificate arrived and verified with the default bundle. The same holds for a [Residential Proxy](https://proxynet.io/residential-proxy) gateway: the exit IP changes, the site's certificate does not, so a certificate error on one site follows you through every exit IP.

## What do you do about hostname mismatch and expired certificates?

Fix the URL or the server, not the client. `Hostname mismatch` means the certificate does not list the name you called: a typo, an internal alias, a staging host on a production certificate, or a CDN that serves another customer's certificate on a shared IP. `IP address mismatch` appears when you call `https://10.0.0.5/` and the certificate only lists names; call the name instead.

`certificate has expired` and `certificate is not yet valid` compare the certificate dates with your clock. If many sites fail at once with one of these, check the system time first, which is common on fresh virtual machines and devices with a dead clock battery. If only one site fails, its owner has to renew. For your own internal servers, add every name and IP you call to the subject alternative names when you issue the certificate.

## How do you fix the PEM lib error with client certificates?

Pass the client certificate and its private key together, either as one file that holds both or as a tuple:

```python
r = requests.get(
    "https://mtls.example.test/api",
    cert=("certs/client.crt", "certs/client.key"),  # certificate first, then the key
    verify="certs/internal-root.pem",
    timeout=10,
)
```

In our test, a certificate file without its key produced `SSLError(SSLError(524297, '[SSL] PEM lib (_ssl.c:4129)'))`, and a wrong path raised `OSError: Could not find the TLS certificate file, invalid path`. The key must not be encrypted: the Requests documentation states that it does not support encrypted keys. A wrong `verify` path gives its own message, `Could not find a suitable TLS CA certificate bundle, invalid path`.

## A complete script: one bundle, retries that skip TLS errors

The script below builds a session with one CA bundle, ignores environment overrides, retries real network failures and server errors, and stops at once on a certificate error. Retrying a TLS failure only repeats the same handshake: against a server with an expired certificate, `Retry(total=3)` made four handshakes in our test, while `other=0` stopped after one.

```python
"""Verified HTTPS session for Requests: one CA bundle, retries that skip certificate errors."""
import sys

import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry

CA_BUNDLE = "ca-bundle-plus-corp.pem"  # certifi roots + your company root, or True for certifi only

def build_session(ca_bundle=CA_BUNDLE, proxy_url=None):
    session = requests.Session()
    session.verify = ca_bundle
    session.trust_env = False  # REQUESTS_CA_BUNDLE and *_PROXY no longer override the values above
    if proxy_url:
        session.proxies = {"http": proxy_url, "https": proxy_url}
    retry = Retry(
        total=4,
        connect=3,
        read=2,
        other=0,  # TLS errors count as "other": a bad certificate stays bad, so fail at once
        status=3,
        status_forcelist=(502, 503, 504),
        backoff_factor=0.5,
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount("https://", adapter)
    session.mount("http://", adapter)
    return session

def fetch(session, url):
    try:
        response = session.get(url, timeout=(5, 20))
        response.raise_for_status()
        return response
    except requests.exceptions.SSLError as err:  # catch before ConnectionError: SSLError is a subclass
        print(f"TLS check failed for {url}: {err}", file=sys.stderr)
    except requests.exceptions.ProxyError as err:
        print(f"Proxy problem: {err}", file=sys.stderr)
    except requests.exceptions.ConnectionError as err:
        print(f"Network problem: {err}", file=sys.stderr)
    return None

if __name__ == "__main__":
    proxy = sys.argv[2] if len(sys.argv) > 2 else None  # e.g. http://user:pass@pr.proxynet.io:8000
    s = build_session(proxy_url=proxy)
    r = fetch(s, sys.argv[1] if len(sys.argv) > 1 else "https://api.ipify.org?format=json")
    if r is not None:
        print(r.status_code, r.text.strip())
```

On our machine it printed `200 {"ok": true}` for the local server signed by our test root, the `certificate has expired` line for the expired one, and the exit IP from `api.ipify.org` through the re-signing proxy. Called with an `https://` proxy URL, it printed the `Proxy problem` branch. Set `CA_BUNDLE = True` if you only call public sites.

## Why is verify=False not the fix?

Because it turns off every check above: any certificate for any name is accepted, including one from someone on the same network who wants to read or change the traffic. The [Requests documentation on certificate verification](https://requests.readthedocs.io/en/latest/user/advanced/#ssl-cert-verification) warns that it makes the application vulnerable to man-in-the-middle attacks.

Use it for one thing: a single run against your own test server, to prove that verification is the problem. If the request then works, the cause is the bundle, the name or the dates, and the table above tells you which. Requests also prints `InsecureRequestWarning: Unverified HTTPS request is being made to host ...` on each such call; silencing it with `urllib3.disable_warnings()` hides the one reminder that the check is off. Clearing `VERIFY_X509_STRICT` for every connection has the same effect on a smaller scale: it hides a broken certificate instead of getting it replaced.

## Where you run into SSLError

- **Company laptops:** a TLS-inspecting gateway re-signs traffic, and every Requests call fails while the browser works.
- **Docker and CI:** a fresh image pins an old certifi, or an `ENV REQUESTS_CA_BUNDLE` line points at a file that is not in the image.
- **Python upgrades:** moving to 3.13 rejects an older internal or gateway CA that worked on 3.12.
- **API testing with a debugging proxy:** mitmproxy or Burp Suite are running, but their root is not in the bundle.
- **Proxy setup:** an `https://` proxy URL for a proxy that only speaks HTTP.
- **Internal services:** dashboards, registries and APIs signed by a private CA, often called by IP.

## Common mistakes

- **Pointing `verify` or `REQUESTS_CA_BUNDLE` at the company root alone.** Public sites then fail as soon as traffic stops going through the gateway.
- **Setting `session.verify` and forgetting the environment.** `REQUESTS_CA_BUNDLE` wins unless you pass `verify` per request or set `trust_env = False`.
- **Upgrading certifi in the wrong environment.** Run pip with the same interpreter, `python -m pip`, inside the virtual environment.
- **Retrying TLS errors.** A retry loop around a certificate failure only adds handshakes and delay.
- **Catching `ConnectionError` before `SSLError`.** The certificate cause disappears into a generic network message.
- **Shipping `verify=False` from a test into production.**

## Decision guide

| What you see | What to do |
|---|---|
| `unable to get local issuer certificate`, public site | Upgrade certifi; check for TLS inspection |
| Same error on the office network only | Combined bundle with the company root |
| `self-signed certificate in certificate chain` | Add that root (gateway, debugging tool or private CA) |
| `Hostname mismatch` or `IP address mismatch` | Call the name the certificate lists |
| `certificate has expired` on many sites | Fix the system clock |
| `Basic Constraints … not marked critical` on 3.13 | Get the CA certificate reissued |
| `WRONG_VERSION_NUMBER` with a proxy | Proxy URL with `http://` |
| `PEM lib` | `cert=(certificate, key)`, unencrypted key |
| Works on one machine only | Compare `REQUESTS_CA_BUNDLE` and certifi version |

## Frequently asked questions

### How do I fix SSLError CERTIFICATE_VERIFY_FAILED in Python requests?

Read the reason after `certificate verify failed:`. For a missing issuer, update certifi or pass `verify=` with a bundle that holds the missing root next to the certifi roots; for a name or date problem, fix the URL, the server or your clock.

### Is verify=False safe in Python requests?

No. It accepts any certificate, so anyone on the network path can read or change the traffic. Use it only for one diagnostic run against your own server, then turn verification back on.

### Why does Python requests fail when the browser opens the site?

The browser reads the operating system's store and repairs incomplete chains; Requests reads only certifi. A company root installed by IT, or a missing intermediate, therefore affects only the script. The truststore package makes Requests read the system store.

### What is the difference between SSLError and SSLCertVerificationError?

`SSLCertVerificationError` is the case where the certificate check failed. A plain `SSLError` is a handshake that broke for another reason, such as `WRONG_VERSION_NUMBER` or a protocol mismatch, so the fix is a URL, port or server setting rather than a CA bundle.

### Can a proxy cause SSLError in Python requests?

Yes, in two ways: a proxy that re-signs TLS, whose root you must add to your bundle, or a proxy URL written with `https://` for an HTTP proxy, which ends in `WRONG_VERSION_NUMBER`. A tunnelling [HTTPS Proxy](https://proxynet.io/https-proxy) passes the site's certificate through unchanged.

### Where does Python requests look for CA certificates?

In the `cacert.pem` file of the certifi package, shown by `python -m certifi`. A `verify=` path on the request, `Session.verify`, `REQUESTS_CA_BUNDLE` or `CURL_CA_BUNDLE` replace it; `SSL_CERT_FILE` and the operating system store are not read without truststore.

## Summary

An `SSLError` from Requests is a failed TLS check, and the reason after `certificate verify failed:` tells you which part failed: the bundle, the name, the dates or the protocol. Update certifi, combine your company or internal root with the certifi roots, watch for `REQUESTS_CA_BUNDLE`, write proxy URLs with `http://`, and keep verification on. For gateways that tunnel HTTPS without touching certificates, see our [proxy services](/proxy).
