How to pass params in python lambda function POST API request

Viewed 26

I am having a POST API URL. Now, I want to send params to this POST API URL using Python Lambda function 3.9. How can I achieve this? I am new to programming, so I did this using postman. Now I want to convert this into python code using urllib.requests library.

To do: I need to pass these four parameters to get the bearer token. From the bearer token, I will take the access token value from the response.

Sample JSON response from POST API request

{
"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IkpXVFNpZ25pbmdDZXJ0LTIwMjAtU1RHIiwieDV0IjoiY3hPcEowNGx5NWJIXzFtQ3pjVGx5OTdKMzFnIiwicGkuYXRtIjoiOCJ9.eyJzY29wZSI6WyJpb3A6ZXZlbnQtbWFuYWdlbWVudCJdLCJjbGllbnRfaWQiOiJzZXJ2aWNlbm93LWNsaWVudC1zdGFnZSIsImlzcyI6Imh0dHBzOi8vd2Vic2VjLXN0Zy5jYWJsZS5jb21jYXN0LmNvbSIsImV4cCI6MTY2Mzc3MDk1M30.KlxYv2G6PKAjmLQAm9m71Pr1WW9QTehS2VsaIleXSz1WelQaK1QFK2uiDs32l_O0SAMbxq_LoKh1rlfIyYuHcS9iZSTTvxMlVVMT-uheK4AT96bQBASmv01YGdH4010kuYXMBhVp0OTjSud0XaPNJtNfTJqU7jPC91tGCPRa0znShOhFvHJ_TCA2PdxwO0f6nkjjEuHXZR21GSSfNYhDS1t1lD7j_qe93DRwc4aJzgu85JJxviUwoQBfDimFewZes4A4mRKk9L0UMAgbOW_LOa8twcWyHvt_Doz_Qh31VLaTv9zDmvxBYhc2c0bXUIq935QRsf55pjd9JHyi-ZrBlw",
"token_type": "Bearer",
"expires_in": 7199

}

I have tried something like this.

def getOAuthAccessTokenFromWebsec(data):
try:
    values = data
    encoded = urllib.parse.urlencode(values).encode("utf-8")
    req = urllib.request.Request('https://websec.com/as/token.oauth2',
                                 headers={'Content-Type': 'application/x-www-form-urlencoded'}, method='POST')

    with urllib.request.urlopen(req, data=encoded) as f:
        resp = f.read()
        webseccreds = json.loads(resp)
        bearertoken = webseccreds['access_token']
        print(bearertoken)
        return bearertoken

except IOError as e:
    print(e)

Postman Screenshot

0 Answers
Related