Disable InsecureRequestWarning in Python

InsecureRequestWarning is a warning that occurs when a request is made without certificate verification. In Python, this warning happens for requests sent from requests and urllib libraries. By default, both libraries implement SSL verification to enable a secured connection.

Note: Sending requests without verification of certificates exposes you to security threats like man-in-the-middle attacks. It is best to avoid this method for scripts used at the production level or when sending and receiving personal data.

Here is a simple example of how we can reproduce the warning.

Output:

InsecureRequestWarning: Unverified HTTPS request is being made to host 'api.github.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
<Response [200]>

The request was sent successfully (shown by a status code of 200 on the response), but the requests library issues a warning that the HTTPS request is unverified. This is because we have verify=False.

We will discuss the following items regarding how to disable InsecureRequestWarning.

  • Suppress InsecureRequestWarning in requests,
  • Disable InsecureRequestWarning in the urllib package,
  • Eliminate InsecureRequestWarning using the warnings package, and,
  • Remove InsecureRequestWarning by explicitly issuing CA bundles for verification.

Suppress InsecureRequestWarning in requests

In this case, we need to add one line, as shown in the code snippet below. Once the warnings are disabled, we can send requests without SSL verification without requests giving InsecureRequestWarning.

Output:

<Response [200]>

Note: This method suppresses all the warnings from requests.

Disable InsecureRequestWarning in the urllib package

In this case, we need to import the urllib3 package and use it to disable warnings, as shown below.

Output:

<http.client.HTTPResponse object at 0x7f127492f7f0>

Eliminate InsecureRequestWarning using the warnings package

Let’s revisit the InsecureRequestWarning message shown at the beginning of the article.

InsecureRequestWarning: Unverified HTTPS request is being made to host ‘api.github.com’. Adding certificate verification is strongly advised…

The warnings package will take the warning message (it comes after the warning name) and filter the warnings accordingly. Here is an example,

Output:

<Response [200]>

The advantage of this method is that it filters specific warnings, not all of them in one go.

Remove InsecureRequestWarning by explicitly issuing CA bundles for verification

This is a manual way of SSL verification. Download the bundle from https://mkcert.org/generate/. If you can’t get the file from that link, follow these steps:

Output:

<Response [200]>