0

I've created the following code, that pulls Cryptocurrency prices from the CoinGecko api and parses the bits I need in JSON

btc = requests.get("https://api.coingecko.com/api/v3/coins/bitcoin")
btc.raise_for_status()
jsonResponse = btc.json() # print(response.json()) for debug
btc_marketcap=(jsonResponse["market_data"]["market_cap"]["usd"])

This works fine, except I then need to duplicate the above 4 lines for every currency which is getting long/messy & repetitive.

After researching I felt an approach was to store the coins in an array, and loop through the array replacing bitcoin in the above example with each item from the array.

symbols = ["bitcoin", "ethereum", "sushi", "uniswap"]
for x in symbols:
    print(x)

This works as expected, but I'm having issues substituting bitcoin/btc for x successfully.

Any pointers appreciated, and whether this is the best approach for what I am trying to achieve

Proof
  • 3
  • 1
  • You don't "substitute bitcoin" with `x`, you append `x` to `"https://api.coingecko.com/api/v3/coins/"`. – Tomalak Jan 25 '21 at 12:57
  • Does this answer your question? [How do I put a variable inside a string?](https://stackoverflow.com/questions/2960772/how-do-i-put-a-variable-inside-a-string) i.e. `f"https://api.coingecko.com/api/v3/coins/{x}"` – Tomerikoo Jan 25 '21 at 13:01

1 Answers1

0

Something like this could work. Basically, just put the repeated part inside a function and call it with the changing arguments (currency). The substitution of the currency can be done for example with f-strings:

def get_data(currency):
    btc = requests.get(f"https://api.coingecko.com/api/v3/coins/{currency}")
    btc.raise_for_status()
    return btc.json()["market_data"]["market_cap"]["usd"]
    
for currency in ["bitcoin", "ethereum", "sushi", "uniswap"]:
    print(get_data(currency))
Niko Föhr
  • 28,336
  • 10
  • 93
  • 96
  • 1
    @Proof Please see [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – Tomerikoo Jan 25 '21 at 13:36