pythonpython-2.7python-requestsurllib3

How to pass data to urllib3 POST request method?


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.


Solution

  • 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'})