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:

The easiest way to do Web Scraping

Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


Try ProxiesAPI for free

curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
...

X

Don't leave just yet!

Enter your email below to claim your free API key: