ZetCode

Python urllib3

last modified November 29, 2026 Python 3.15

In this article we show how to send HTTP requests in Python with the urllib3 library.

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.

The urllib3 library is an HTTP client with connection pooling, thread safety, TLS verification, retries, redirects, multipart file uploads, and streaming of large responses. Many other libraries are built on it, including Requests. It is lower level than Requests: it does not raise exceptions for error status codes and does not manage cookies or sessions.

The examples in this article send requests to httpbin.org, a service that echoes the details of the request back to the client, so the outputs can differ slightly over time. We install the library with pip, preferably in a virtual environment.

$ pip install urllib3

First request

Since version 2.0, the urllib3.request function sends a single request without any setup.

first_request.py
import urllib3

print(urllib3.__version__)

resp = urllib3.request('GET', 'https://example.com')

print(resp.status)
print(resp.headers['Content-Type'])
print(len(resp.data))

The program prints the version of the library and sends a GET request to example.com.

resp = urllib3.request('GET', 'https://example.com')

The first argument is the HTTP method, the second one the URL. The function returns an HTTPResponse object.

print(resp.status)
print(resp.headers['Content-Type'])
print(len(resp.data))

The status attribute holds the status code, headers is a case-insensitive dictionary of response headers, and data contains the body as bytes. HTTPS certificates are verified by default.

$ python first_request.py
2.8.0
200
text/html; charset=utf-8
577

PoolManager

The urllib3.request function uses a shared, module-level pool. Programs usually create their own PoolManager. It keeps a pool of connections for every host and reuses them, which saves the TCP and TLS handshake on subsequent requests.

pool_manager.py
import urllib3

http = urllib3.PoolManager()

for path in ('/get', '/uuid', '/ip'):
    resp = http.request('GET', f'https://httpbin.org{path}')
    print(path, resp.status)

pool = http.connection_from_url('https://httpbin.org')
print(f'connections opened: {pool.num_connections}')
print(f'requests sent: {pool.num_requests}')

We send three requests to the same host and then inspect the connection pool of that host.

http = urllib3.PoolManager()

A program normally needs only one PoolManager; it is safe to share it between threads.

pool = http.connection_from_url('https://httpbin.org')
print(f'connections opened: {pool.num_connections}')
print(f'requests sent: {pool.num_requests}')

The connection_from_url method returns the pool for the host. All three requests went through a single connection.

$ python pool_manager.py
/get 200
/uuid 200
/ip 200
connections opened: 1
requests sent: 3

Reading JSON

The response body is raw bytes. Text is obtained with resp.data.decode(); for JSON, the json method decodes the body and parses it in one step.

read_json.py
import urllib3

http = urllib3.PoolManager()

resp = http.request('GET', 'https://httpbin.org/json')
data = resp.json()

slideshow = data['slideshow']
print(slideshow['title'])

for slide in slideshow['slides']:
    print(f"- {slide['title']}")

The /json endpoint returns a sample JSON document describing a slide show.

data = resp.json()

The method returns Python dictionaries and lists. It raises an exception if the body is not valid JSON.

$ python read_json.py
Sample Slide Show
- Wake up to WonderWidgets!
- Overview

Query parameters

Query parameters are the part of a URL after the ? character. They are name=value pairs separated with &, and special characters in them must be encoded.

query_params.py
import urllib3

http = urllib3.PoolManager()

params = {'name': 'Peter Novak', 'age': 23}
resp = http.request('GET', 'https://httpbin.org/get', fields=params)

data = resp.json()
print(data['url'])
print(data['args'])

We send two parameters to the /get endpoint, which returns the final URL and the parsed parameters.

resp = http.request('GET', 'https://httpbin.org/get', fields=params)

For GET, HEAD, and DELETE requests, the fields dictionary is encoded into the query string. The space is encoded as + and the number becomes a string.

$ python query_params.py
https://httpbin.org/get?name=Peter+Novak&age=23
{'age': '23', 'name': 'Peter Novak'}

HEAD request

A HEAD request asks only for the headers of a resource. It is useful for checking whether a resource exists or has changed without downloading it.

head_request.py
import urllib3

http = urllib3.PoolManager()

resp = http.request('HEAD', 'https://example.com')

print(resp.status)
print(len(resp.data))

for name in ('Content-Type', 'Server', 'Last-Modified'):
    print(f'{name}: {resp.headers.get(name)}')

We send a HEAD request to example.com and print a few response headers.

print(f'{name}: {resp.headers.get(name)}')

The get method returns None for a missing header instead of raising a KeyError. The body of the response is empty.

$ python head_request.py
200
0
Content-Type: text/html; charset=utf-8
Server: cloudflare
Last-Modified: Wed, 25 Nov 2026 23:44:53 GMT

POST form data

The POST method sends data to the server, for example the fields of a web form. For POST and PUT requests, the fields parameter puts the data into the request body.

post_form.py
import urllib3

http = urllib3.PoolManager()

form = {'name': 'Peter Novak', 'occupation': 'gardener'}
resp = http.request('POST', 'https://httpbin.org/post',
                    fields=form, encode_multipart=False)

data = resp.json()
print(data['headers']['Content-Type'])
print(data['form'])

We send two form fields to the /post endpoint.

resp = http.request('POST', 'https://httpbin.org/post',
                    fields=form, encode_multipart=False)

By default, the body is encoded as multipart/form-data. With encode_multipart=False, it uses the application/x-www-form-urlencoded encoding of simple HTML forms.

$ python post_form.py
application/x-www-form-urlencoded
{'name': 'Peter Novak', 'occupation': 'gardener'}

POST JSON

Web APIs usually accept JSON. The json parameter serializes a Python object into the body and sets the Content-Type header.

post_json.py
import urllib3

http = urllib3.PoolManager()

user = {'name': 'Peter Novak', 'skills': ['pruning', 'grafting']}
resp = http.request('POST', 'https://httpbin.org/post', json=user)

data = resp.json()
print(data['headers']['Content-Type'])
print(data['json'])

We send a dictionary with a nested list. The /post endpoint returns the parsed JSON body in its json field.

resp = http.request('POST', 'https://httpbin.org/post', json=user)

Before version 2.0, we had to call json.dumps, encode the string, and set the header ourselves.

$ python post_json.py
application/json
{'name': 'Peter Novak', 'skills': ['pruning', 'grafting']}

Request headers

Headers can be set for all requests of a PoolManager or for a single request. The /headers endpoint returns the headers it received.

request_headers.py
import urllib3

headers = {'User-Agent': 'zetcode-client/1.0', 'Accept': 'application/json'}
http = urllib3.PoolManager(headers=headers)

resp = http.request('GET', 'https://httpbin.org/headers')
sent = resp.json()['headers']
print(sent['User-Agent'], sent['Accept'])

resp = http.request('GET', 'https://httpbin.org/headers',
                    headers={'User-Agent': 'other/2.0'})
sent = resp.json()['headers']
print(sent['User-Agent'], sent.get('Accept'))

The pool manager sends a custom user agent and an Accept header with every request. The second request passes its own headers.

http = urllib3.PoolManager(headers=headers)

These are the default headers of all requests made through the manager.

resp = http.request('GET', 'https://httpbin.org/headers',
                    headers={'User-Agent': 'other/2.0'})

Headers given to a request replace the default headers completely; they are not merged. The second request therefore does not send the Accept header.

$ python request_headers.py
zetcode-client/1.0 application/json
other/2.0 None

Basic authentication

The make_headers helper builds common headers, such as Authorization for basic authentication, User-Agent, or Accept-Encoding.

basic_auth.py
import urllib3

http = urllib3.PoolManager()
url = 'https://httpbin.org/basic-auth/peter/s3cret'

resp = http.request('GET', url)
print(resp.status)

headers = urllib3.make_headers(basic_auth='peter:s3cret')
print(headers)

resp = http.request('GET', url, headers=headers)
print(resp.status, resp.json())

The endpoint requires the user name peter and the password s3cret. We try it first without and then with credentials.

headers = urllib3.make_headers(basic_auth='peter:s3cret')

The credentials are Base64-encoded, not encrypted, so basic authentication should only be used over HTTPS.

$ python basic_auth.py
401
{'authorization': 'Basic cGV0ZXI6czNjcmV0'}
200 {'authenticated': True, 'user': 'peter', 'authorized': True}

Status codes

Response status codes are grouped in five classes: informational (100–199), successful (200–299), redirects (300–399), client errors (400–499), and server errors (500–599). The urllib3 library does not raise an exception for error codes; we must check the status ourselves.

status_codes.py
import urllib3

http = urllib3.PoolManager()

for code in (200, 404, 500):
    resp = http.request('GET', f'https://httpbin.org/status/{code}')

    if resp.status >= 400:
        print(f'{code}: request failed with status {resp.status}')
    else:
        print(f'{code}: ok')

The /status endpoint returns the requested status code.

if resp.status >= 400:
    print(f'{code}: request failed with status {resp.status}')

Codes 400 and above signal an error. The request itself succeeded, so no exception was raised.

$ python status_codes.py
200: ok
404: request failed with status 404
500: request failed with status 500

Timeouts

By default, a request waits for the server indefinitely. A Timeout object limits the time for connecting and for reading the response separately.

timeouts.py
import time

import urllib3

http = urllib3.PoolManager(retries=False)
timeout = urllib3.Timeout(connect=2.0, read=1.0)

for delay in (0, 3):
    start = time.perf_counter()
    try:
        resp = http.request('GET', f'https://httpbin.org/delay/{delay}',
                            timeout=timeout)
        print(f'delay {delay}: status {resp.status}')
    except urllib3.exceptions.ReadTimeoutError as e:
        elapsed = time.perf_counter() - start
        print(f'delay {delay}: gave up after {elapsed:.1f} s')
        print(f'  {type(e).__name__}')

The /delay endpoint responds after the given number of seconds. The read timeout is one second.

http = urllib3.PoolManager(retries=False)
timeout = urllib3.Timeout(connect=2.0, read=1.0)

We disable retries so that the timeout error is raised directly. With retries enabled, urllib3 would retry the request and finally raise MaxRetryError. A plain number, such as timeout=5, sets both limits.

except urllib3.exceptions.ReadTimeoutError as e:

The exceptions are defined in the urllib3.exceptions module. The read timeout applies to each read from the socket, not to the whole download.

$ python timeouts.py
delay 0: status 200
delay 3: gave up after 1.0 s
  ReadTimeoutError

Retries

The Retry class controls how failed requests are repeated. It can retry connection errors and responses with selected status codes, and it waits longer between the attempts.

retries.py
import urllib3
from urllib3.util import Retry

retry = Retry(total=3, backoff_factor=0.2, status_forcelist=[503])
http = urllib3.PoolManager(retries=retry)

try:
    http.request('GET', 'https://httpbin.org/status/503')
except urllib3.exceptions.MaxRetryError as e:
    print(f'failed: {e.reason}')

retry = Retry(total=3, backoff_factor=0.2, status_forcelist=[503],
              raise_on_status=False)
resp = http.request('GET', 'https://httpbin.org/status/503', retries=retry)
print(f'final status: {resp.status}')

for attempt in resp.retries.history:
    print(f'  {attempt.method} {attempt.url} -> {attempt.status}')

The server always answers with 503 Service Unavailable. We retry the request three times, first with an exception at the end and then without it.

retry = Retry(total=3, backoff_factor=0.2, status_forcelist=[503])

The status_forcelist parameter lists status codes that trigger a retry. The backoff_factor makes the client sleep between attempts for exponentially growing times. When all retries are used up, urllib3 raises MaxRetryError.

for attempt in resp.retries.history:
    print(f'  {attempt.method} {attempt.url} -> {attempt.status}')

With raise_on_status=False, the last response is returned instead. Its retries.history records every attempt that was retried: the first request and two retries; the third retry produced the final response.

$ python retries.py
failed: too many 503 error responses
final status: 503
  GET /status/503 -> 503
  GET /status/503 -> 503
  GET /status/503 -> 503

Redirects

A redirect is a response with a 3xx status code and a Location header pointing to another URL. Redirects are followed automatically, and they count against the retry limit, which allows three redirects by default.

redirects.py
import urllib3

http = urllib3.PoolManager()
url = 'https://httpbin.org/redirect/3'

resp = http.request('GET', url)
print(resp.status, resp.json()['url'])

for step in resp.retries.history:
    print(f'  {step.status} {step.url} -> {step.redirect_location}')

resp = http.request('GET', url, redirect=False)
print(resp.status, resp.headers['Location'])

The /redirect/3 endpoint redirects three times before ending at /get.

for step in resp.retries.history:
    print(f'  {step.status} {step.url} -> {step.redirect_location}')

Each redirect is recorded in the retry history with the redirect target.

resp = http.request('GET', url, redirect=False)

With redirect=False, the client returns the first 302 response, and we can read the Location header ourselves.

$ python redirects.py
200 https://httpbin.org/get
  302 https://httpbin.org/redirect/3 -> /relative-redirect/2
  302 https://httpbin.org/relative-redirect/2 -> /relative-redirect/1
  302 https://httpbin.org/relative-redirect/1 -> /get
302 /relative-redirect/2

Binary data

The data attribute holds the body as bytes, so binary files can be written to disk directly.

download_image.py
from pathlib import Path

import urllib3

http = urllib3.PoolManager()

resp = http.request('GET', 'https://httpbin.org/image/png')
print(resp.headers['Content-Type'])

path = Path('pig.png')
path.write_bytes(resp.data)

print(f'{path}: {path.stat().st_size} bytes')
print(resp.data[:8])

We download a PNG image and save it to a file.

path.write_bytes(resp.data)

The write_bytes method of Path writes the bytes unchanged. The first eight bytes are the PNG signature.

$ python download_image.py
image/png
pig.png: 8090 bytes
b'\x89PNG\r\n\x1a\n'

Streaming

By default, the whole body is read into memory before the request returns. For large files, we turn this off with preload_content=False and read the body in chunks.

streaming.py
import hashlib

import urllib3

http = urllib3.PoolManager()
url = 'https://httpbin.org/bytes/100000?seed=42'

resp = http.request('GET', url, preload_content=False)

digest = hashlib.sha256()
chunks = 0
total = 0

with open('random.bin', 'wb') as f:
    for chunk in resp.stream(16384):
        f.write(chunk)
        digest.update(chunk)
        chunks += 1
        total += len(chunk)

resp.release_conn()

print(f'{chunks} chunks, {total} bytes')
print(f'sha256: {digest.hexdigest()[:16]}...')

We download 100,000 random bytes in chunks of 16 KiB, write them to a file, and compute their SHA-256 hash on the way. The seed parameter makes the server return the same bytes every time.

for chunk in resp.stream(16384):

The stream method yields chunks of at most the given size, so the program never holds more than one chunk in memory.

resp.release_conn()

A streamed response keeps its connection until the body is read. The release_conn method returns the connection to the pool so that it can be reused.

$ python streaming.py
7 chunks, 100000 bytes
sha256: 545198f6f4e4ed36...

File upload

Files are uploaded with multipart/form-data requests. In the fields dictionary, a file is given as a tuple with the file name, the data, and optionally the MIME type.

upload_file.py
from pathlib import Path

import urllib3

Path('notes.txt').write_text('buy seeds\nwater the roses\n')

http = urllib3.PoolManager()

fields = {
    'author': 'Peter Novak',
    'file': ('notes.txt', Path('notes.txt').read_bytes(), 'text/plain'),
}
resp = http.request('POST', 'https://httpbin.org/post', fields=fields)

data = resp.json()
print(data['headers']['Content-Type'].split(';')[0])
print(data['form'])
print(data['files'])

We create a small text file and upload it together with a regular form field.

'file': ('notes.txt', Path('notes.txt').read_bytes(), 'text/plain'),

The tuple turns the field into a file part of the multipart body. The /post endpoint returns regular fields under form and files under files.

$ python upload_file.py
multipart/form-data
{'author': 'Peter Novak'}
{'file': 'buy seeds\nwater the roses\n'}

Concurrent requests

A PoolManager is thread-safe, so a single instance can serve many threads. Each pool keeps at most maxsize idle connections per host; it should be at least the number of threads.

threaded_requests.py
import time
from concurrent.futures import ThreadPoolExecutor

import urllib3

http = urllib3.PoolManager(maxsize=5)


def fetch(n):
    resp = http.request('GET', f'https://httpbin.org/delay/1?n={n}')
    return n, resp.status


start = time.perf_counter()

with ThreadPoolExecutor(max_workers=5) as pool:
    for n, status in pool.map(fetch, range(1, 6)):
        print(f'request {n}: {status}')

elapsed = time.perf_counter() - start
print(f'5 requests in {elapsed:.0f} s')

conn_pool = http.connection_from_url('https://httpbin.org')
print(f'connections opened: {conn_pool.num_connections}')

We send five requests, each taking one second on the server, from a pool of five threads.

http = urllib3.PoolManager(maxsize=5)

The default maxsize is 1. With five threads, the extra connections would be opened anyway, but closed after use; urllib3 logs a Connection pool is full warning through the logging module.

with ThreadPoolExecutor(max_workers=5) as pool:
    for n, status in pool.map(fetch, range(1, 6)):

The requests run concurrently, so all five finish in about one second instead of five. The map method returns the results in the order of the inputs.

$ python threaded_requests.py
request 1: 200
request 2: 200
request 3: 200
request 4: 200
request 5: 200
5 requests in 1 s
connections opened: 5

Source

urllib3 documentation
urllib3 user guide

In this article we have sent HTTP requests with urllib3. We have used a PoolManager, read JSON, sent query parameters, forms, JSON, and files, set headers, and handled status codes, timeouts, retries, and redirects. The higher-level Requests and httpx libraries are covered in their own articles; the standard library's own client is shown in GET/POST request, and more on parallel downloads is in concurrent HTTP requests.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.