How to pass data to urllib3 POST request method?
Asked Answered
P

1

5

I want to use urllib3 library for making POST request over requests library since it has connection pooling and retries etc. But I couldn't find any substitute of following POST request.

import requests
result = requests.post("http://myhost:8000/api/v1/edges", json={'node_id1':"VLTTKeV-ixhcGgq53", 'node_id2':"VLTTKeV-ixhcGgq51", 'type': 1 })

This is working fine with requests library but I couldn't convert this into urllib3 request. I tried

import json
import urllib3
urllib3.PoolManager().request("POST","http://myhost:8000/api/v1/edges", body=json.dumps(dict(json={'node_id1':"VLTTKeV-ixhcGgq53", 'node_id2':"VLTTKeV-ixhcGgq51", 'type': 1 })))

Problem is with passing raw json data with json as key in POST request.

Phytobiology answered 30/8, 2015 at 11:52 Comment(0)
A
11

You don't need the json keyword argument; you are wrapping your dictionary in another dictionary there.

You'll also need to add a Content-Type header, set it to application/json:

http = urllib3.PoolManager()
data = {'node_id1': "VLTTKeV-ixhcGgq53", 'node_id2': "VLTTKeV-ixhcGgq51", 'type': 1})
r = http.request(
    "POST", "http://myhost:8000/api/v1/edges", 
    body=json.dumps(data),
    headers={'Content-Type': 'application/json'})
Anderson answered 30/8, 2015 at 11:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.