DEV Community

Cover image for Getting Started With APIs - Bonus Tasks
Abraham Gumba
Abraham Gumba

Posted on • Updated on

Getting Started With APIs - Bonus Tasks

The Story So Far

In our first article in this series, we looked at what APIs are and what they are used for. In the second article, we wrote a simple Python program that fetches some data from an API.

In this article, we will introduce a loop, so that we can get historical data over a period of time, then we will use this historical data and matplotlib to create a chart.

We are using the API from ExchangeRatesAPI.io because their free plan allows us to fetch historical data.

In previous steps, we already created an account at ExchangeRatesAPI.io and got a free API Key. We also installed the requests library and matplotlib, and imported them into the program we wrote. The program fetches exchange rate data for a specified date and gives us the data in JSON format, which we then convert into a nested Python dictionary.

Here is the program we developed in the last article.

import requests
import matplotlib.pyplot as plt

my_key = "my_very_secret_key:-)"

my_url="http://api.exchangeratesapi.io/v1/2022-06-15?access_key="+my_key

response = requests.get(my_url)

my_dict = response.json()

print(my_dict)
# Get the rates nested dictionary
my_dict['rates']

# Get the Kenya Shilling rate from the rates dictionary
my_dict['rates']['KES'] # Of course, you can change this to a currency of your choice.
Enter fullscreen mode Exit fullscreen mode

Image description

The Task Now

Now, the URL that we use in our request is similar to the one below.
my_url="http://api.exchangeratesapi.io/v1/2022-06-15?access_key="+my_key

Notice that it has a date hard-coded in it. In this example it is 2022-06-15, in the format specified by the API provider.
We are interested in getting values for different years. That means we need to send several requests, each with a different date. It also means that we need to replace the fixed date in our URL with a variable one.

We will use a for loop to do these two things.

Before we do that, though, we will need two lists: one that will contain the years we are interested in, and another that will contain the exchange rate values.

my_years = []
exch_rates = []
Enter fullscreen mode Exit fullscreen mode

Now we can create our loop.

for my_year in range(2000, 2024):
   my_url="http://api.exchangeratesapi.io/v1/"+str(my_year)+"-06-15?access_key="+my_key
Enter fullscreen mode Exit fullscreen mode

We have replaced the hard-coded year with a variable that ranges from 2000 to 2023.
(The range function stops 1 number before the number specified in the second argument).

Get the response, convert to a dictionary and pick out the exchange rate we want.

    response = requests.get(my_url)

    my_dict = response.json()

    exch_rate = my_dict['rates']['KES']
Enter fullscreen mode Exit fullscreen mode

We append the current year in our loop and the exchange rate to the lists we created.

    my_years.append(my_year)
    exch_rates.append(exch_rate)
Enter fullscreen mode Exit fullscreen mode

That's really it for retrieving the data.

In case you are wondering why we retrieve all the exchange rates when we are only interested in one, it's because the free plan on ExchangeratesAPI.io does not allow us to retrieve data for only specified currencies.

Now we use matplotlib to draw a chart of the exchange rate trend, display the chart and also save it as an image file.

# Set the figure size and create the plot
plt.figure(figsize=(8, 6))
plt.plot(my_years, exch_rates, color='red')

# Customize the plot
plt.title("Euro to KES Rates (Years 2000 to 2023)", fontsize='16')
plt.xlabel("Year", fontsize='13', color='green')
plt.ylabel("Euro-KES Rate", fontsize='13', color='blue')
plt.minorticks_on()
plt.grid(True, which='major', linestyle='-', linewidth=0.5)
plt.grid(True, which='minor', linestyle=':', linewidth=0.5)

# Save and show the plot
plt.savefig('EuroExRatesAPI_io.png')
plt.show()
Enter fullscreen mode Exit fullscreen mode

I will not describe the matplotlib commands. They are fairly straightforward, and you can always look up the documentation.

Conclusion and Next Steps

And there it is! We have modified our program to get data for multiple dates, store them, draw a chart, show the chart and also save it as a file.

I hope you found the articles useful.

You could now try a little arithmetic and use this info that was retrieved (for exchange rates against the Euro) to get the exchange rate against a different currency, such as KES to USD.

Or you could simply look for an API that is based on the US Dollar and allow you to retrieve historical data.

You could also learn a bit more about matplotlib and plot different currencies on the same chart.

Or, of course, you could fetch data for something entirely different.
Here is the list of APIs that I shared earlier.
APIsList.

Enjoy your coding!


One-on-One Lessons

If you wish to have one-on-one lessons in Python or PHP or if you need support from time to time as you go through coding lessons from elsewhere, please consider the lessons/service that I offer.

Top comments (0)