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

旧时模样 提交于 2019-12-22 06:36:16

问题


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.


回答1:


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?



来源:https://stackoverflow.com/questions/31778800/how-can-i-make-a-post-request-on-python-with-urllib3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!