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

前端 未结 2 1540
梦谈多话
梦谈多话 2021-01-12 13:52

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úr         


        
2条回答
  •  清酒与你
    2021-01-12 14:19

    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?

提交回复
热议问题