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

前端 未结 2 1541
梦谈多话
梦谈多话 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?

    0 讨论(0)
  • 2021-01-12 14:19

    I ran into this issue when making a call to Gitlab CI. Since the above did not work for me (gave me some kind of error about not being able to concatenate bytes to a string), and because the arguments I was attempting to pass were nested, I thought I would post what ended up working for me:

    API_ENDPOINT = "https://gitlab.com/api/v4/projects/{}/pipeline".format(GITLAB_PROJECT_ID)
    
    API_TOKEN = "SomeToken"
    
    data = {
        "ref": ref,
        "variables": [
            {
                "key": "ENVIRONMENT",
                "value": some_env
            },
            {   "key": "S3BUCKET",
                "value": some_bucket
            },
        ]
    }
    
    req_headers = {
        'Content-Type': 'application/json',
        'PRIVATE-TOKEN': API_TOKEN,
    }
    
    http = urllib3.PoolManager()
    
    encoded_data = json.dumps(data).encode('utf-8')
    
    r = http.request('POST', API_ENDPOINT,
                 headers=req_headers,
                 body=encoded_data)
    
    resp_body = r.data.decode('utf-8')
    resp_dict = json.loads(r.data.decode('utf-8'))
    
    logger.info('Response Code: {}'.format(r.status))
    logger.info('Response Body: {}'.format(resp_body))
    
    if 'message' in resp_body:
        logfile_msg = 'Failed Gitlab Response-- {} {message}'.format(r.status, **resp_dict)
    
    0 讨论(0)
提交回复
热议问题