Home > database >  Why am i getting Object of type method is not JSON serializable when making this api call
Why am i getting Object of type method is not JSON serializable when making this api call

Time:02-18

I am trying to interact with the coinbase api and keep getting "TypeError: Object of type method is not JSON serializable" when trying to print out this json data, I know the get request is correct as it returns a 200 when I remove the json.dumps().

    import requests
    import json


    response = requests.get('https://api.coinbase.com/v2/prices/BTC-USD/buy')
    data = json.dumps(response.json)
    print(data)

CodePudding user response:

Your return is:

{'data': {'base': 'BTC', 'currency': 'USD', 'amount': '40880.98'}}

It has a JSON syntax error

Try this

response = requests.get('https://api.coinbase.com/v2/prices/BTC-USD/buy')
data = response.json()
dataJson = json.dumps(data['data'])
print(dataJson)

CodePudding user response:

Try this:

response = requests.get('https://api.coinbase.com/v2/prices/BTC-USD/buy')
data = json.loads(response.text)
print(data)  # {'data': {'base': 'BTC', 'currency': 'USD', 'amount': '40935.10'}}

CodePudding user response:

It happens when the response of your call is not a json, not all the API calls return the same, some returns an HTML, others just plain text

is suggest you to check the status code of the response

if response.status_code == 200:
    data = json.dumps(response.json)
    print(data)
else:
    print("The call to the API was not successful")
  • Related