Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Data from API and Parsing [closed]

Tags:

python

api

For context, I'm really new to web-development.

Is there a better way of getting the data from this website than removing non-numeric characters from the string you get from .read(), such as shown in this solution and then separating the two numbers?

If the python script is calling the API and getting data, how would you automate that process to refresh the data in a time period (e.g. every minute)?

like image 284
Sentient Avatar asked Dec 19 '22 06:12

Sentient


2 Answers

This data is in JSON format, you can retrieve it as a Python dict using the requests library:

>>> import requests
>>> data = requests.get("https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC,USD,EUR"
                  ).json()
>>> data
{'BTC': 0.1432, 'EUR': 343.04, 'USD': 388.04}

If you want to run it regularly there are a few different options; you could use cron (or taskscheduler on windows), or you could use a loop with time.sleep(60).

like image 181
maxymoo Avatar answered Dec 20 '22 20:12

maxymoo


That data is in JSON format, which is roughly equivalent to a dictionary in Python. I'm not an expert in Python, but I believe that you'll need to import the json module and parse the data with .loads() - then you can access the values as properties of the dictionary.

So for example, your data looks like this:

{"BTC":0.1434,"USD":387.92,"EUR":343.51}

In your script, you'll import json, put the data into a variable, and parse it as a dictionary:

import json

json_string = '{"BTC":0.1434,"USD":387.92,"EUR":343.51}'
parsed_json = json.loads(json_string)

Now if you reference parsed_json, you can access the values:

print parsed_json['BTC'] 
# 0.1434

print parsed_json['EUR']
# 343.51

And so on.

Edit After re-reading your question, I feel like what you are aiming for is some combination of the accepted answer and mine. Here's what I think you're looking for (borrowing from the accepted answer):

>>> import requests

>>> data = requests.get("https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC,USD,EUR"
              ).json()
>>> data['USD']
387.92
>>> data['BTC']
0.1434

The data returned by requests.get() is already parsed, so there's no need to parse it again with json.loads(). To access the value of a dictionary's attribute, type the name of the dictionary and then the attribute in brackets.

like image 35
skwidbreth Avatar answered Dec 20 '22 20:12

skwidbreth