简体   繁体   中英

I can't get data from JSON with python

I can't seem to get the last recorded price from a website API using JSON. I tried finding the error but it seems okay to me. The code is in python This is the Url that I have to GET: https://api.independentreserve.com/Public/GetMarketSummary?primaryCurrencyCode=xbt&secondaryCurrencyCode=aud

Python 3.7

import requests


URL = "https://api.independentreserve.com/Public/GetMarketSummary?"

CurrencyCode = "xbt"
SecondaryCode = "aud"
PARAMS = {'primaryCurrencyCode': CurrencyCode, '&secondaryCurrencyCode': SecondaryCode}
r = requests.get(url=URL, params=PARAMS)

data = r.json()


lastprice = data['LastPrice']


print("Last Price:%s" % lastprice)

here is the fixed code

import requests


URL = "https://api.independentreserve.com/Public/GetMarketSummary?"

CurrencyCode = "xbt"
SecondaryCode = "aud"
PARAMS = {'primaryCurrencyCode': CurrencyCode, 'SecondaryCurrencyCode': SecondaryCode}
r = requests.get(url=URL, params=PARAMS)

data = r.json()


lastprice = data['LastPrice']


print("Last Price:%s" % lastprice)

the problem is in the PARAMS dict. you need to change "&secondaryCurrencyCode" to "SecondaryCurrencyCode" .

if you had printed the data dict, you would see this:

{'Message': 'Secondary Currency Code is required'}

Removing & in "&secondaryCurrencyCode" will fix the issue.

Fixed code below:

import requests

URL = "https://api.independentreserve.com/Public/GetMarketSummary?"

CurrencyCode = "xbt"
SecondaryCode = "aud"
PARAMS = {'primaryCurrencyCode': CurrencyCode, 'secondaryCurrencyCode': SecondaryCode}
r = requests.get(url=URL, params=PARAMS)

data = r.json()


lastprice = data['LastPrice']

print("Last Price:%s" % lastprice)

API is expecting secondaryCurrencyCode not &secondaryCurrencyCode .

You don't need & sign when you use params.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM