Tuesday, August 22, 2023

Colab Python web service : Cannot get expected return with json passing to REST API

Another silly mistake I made due carelessness .
I spent certain hours to just figure out the root-cause : Missing json.dumps when I pass the data.
Originally, I think put json content in header is OK...


#Call Rest API with json data
import requests
import json
import os

baseUrl = 'endpointAddr/api-link'

#Parameters
data = {
   "id":"1234568",
   "currency":"HKD",
   "amount":"1000"
}




#function to call
def callAPI():
    response = requests.post(baseUrl,headers={"Content-Type": "application/json","Authorization": "Bearer xxxxxxxxxxxxxxx"}, data=json.dumps(data))

    if response.status_code == 200:
       print('Access token test :' , response.json())
       authToken = response.json()['access_token']
       print('Access token:', authToken)
       return (authToken)
    else:
        print('Login failed with status code:', response.status_code , response.text)
        return (0)


#Main
response1 = callAPI()
print ('response 1 ' + response1)

No comments:

Post a Comment

Something about Renpy For loop error : expected statement.

 It takes me over hour to debug. The simple fact is that under label, we cannot use For loop. One while is valid to be used under label. To ...