How to Make HTTP POST Requests in Python with urllib3

Feb 1, 2024 ยท 1 min read

The urllib3 library provides a simple way to make HTTP requests in Python. This includes sending POST requests to submit data to APIs and web services.

To make a POST request with urllib3, first install the library:

pip install urllib3

Then import urllib3 and create a PoolManager instance to manage connections:

import urllib3

http = urllib3.PoolManager()

Construct the data you want to submit as a dictionary. For example:

data = {
  'name': 'John Doe',
  'occupation': 'gardener' 
}

To make the POST request, call http.request() and pass "POST" as the method. Provide the URL and the data dictionary:

r = http.request(
  "POST",
  "http://api.example.com/users",
  fields=data   
)

The fields parameter encodes the dictionary as form data.

Check the r.status attribute to see the response status code, 200 means success. Use r.data to access the response content.

if r.status == 200:
  print(r.data)

To post JSON data, use the body parameter instead of fields and set the Content-Type header:

import json

data = json.dumps({'name': 'John Doe'}) 

r = http.request(
  "POST", 
  "http://api.example.com/users",
  body=data,
  headers={'Content-Type': 'application/json'}
)

Browse by language:

Tired of getting blocked while scraping the web?

ProxiesAPI handles headless browsers and rotates proxies for you.
Get access to 1,000 free API credits, no credit card required!