How can I make a Post Request on Python with urllib3?

user1953742 picture user1953742 · Aug 3, 2015 · Viewed 33.7k times · Source

I've been trying to make a request to an API, I have to pass the following body:

{
"description":"Tenaris",
"ticker":"TS.BA",
"industry":"Metalúrgica",
"currency":"ARS"
}

Altough the code seems to be right and it finished with "Process finished with exit code 0", it's not working well. I have no idea of what I'm missing but this is my code:

http = urllib3.PoolManager()
http.urlopen('POST', 'http://localhost:8080/assets', headers={'Content-Type':'application/json'},
                 data={
"description":"Tenaris",
"ticker":"TS.BA",
"industry":"Metalúrgica",
"currency":"ARS"
})

By the way, this the first day working with Python so excuse me if I'm not specific enough.

Answer

shazow picture shazow · Aug 3, 2015

Since you're trying to pass in a JSON request, you'll need to encode the body as JSON and pass it in with the body field.

For your example, you want to do something like:

import json
encoded_body = json.dumps({
        "description": "Tenaris",
        "ticker": "TS.BA",
        "industry": "Metalúrgica",
        "currency": "ARS",
    })

http = urllib3.PoolManager()

r = http.request('POST', 'http://localhost:8080/assets',
                 headers={'Content-Type': 'application/json'},
                 body=encoded_body)

print r.read() # Do something with the response?

Edit: My original answer was wrong. Updated it to encode the JSON. Also, related question: How do I pass raw POST data into urllib3?