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

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

    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)
    

提交回复
热议问题