Skip to Content
Course content

284: Practice Exercise: Building a Currency Converter Using a Live API

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this a dozen times in code reviews with junior devs: they call an API, and then they immediately try to treat the result like a Python dictionary. It's a logical leap, but it's one that will crash your program every single time.

Treating the Response Object Like a Dictionary

When you use the requests library to hit a currency API, you might be tempted to write something like this:

import requests

response = requests.get("https://api.exchangerate-api.com/v4/latest/USD")
# This is where the crash happens
euro_rate = response['rates']['EUR'] 

If you run that, Python will throw a TypeError: 'Response' object is not subscriptable. Why? Because requests.get() doesn't return the data itself; it returns a Response object. This object contains the status code (like 200 or 404), the headers, the cookies, and the raw content. It's the entire envelope, not just the letter inside.

Parsing the JSON Payload for Actual Rates

To get to the actual exchange rates, you have to tell Python to parse the body of that response into a format it understands—usually JSON. In the requests library, there's a built-in method called .json() that does exactly this. It takes the raw string returned by the server and turns it into a native Python dictionary.

Here is how you actually handle it. I always recommend checking the status code first, because if the API is down or your key is expired, trying to parse JSON from an error page will just lead to more crashes.

import requests

url = "https://api.exchangerate-api.com/v4/latest/USD"
response = requests.get(url)

if response.status_code == 200:
    data = response.json() # This is the magic step
    euro_rate = data['rates']['EUR']
    print(f"The current USD to EUR rate is: {euro_rate}")
else:
    print(f"API Error: {response.status_code}")

Notice how we separated the network request from the data extraction. Once data is a dictionary, you can navigate it just like any other Python object. Most currency APIs nest their rates inside a key called 'rates' or 'data', so you'll usually be doing a double-lookup: first for the rates collection, then for the specific currency code (like 'GBP' or 'JPY').

One quick tip: APIs can be temperamental. Always wrap your network calls in a try/except block in production code. A momentary WiFi hiccup shouldn't be the reason your entire application dies.




📋 Practical Task

Project: The Live Multi-Currency Converter

Your task is to build a functional currency converter that interacts with a live API. Instead of hardcoding a single conversion, your program should be flexible enough to handle any currency pair supported by the API.

Requirements:

  • Use the requests library to fetch data from https://api.exchangerate-api.com/v4/latest/[BASE_CURRENCY].
  • Prompt the user to input a base currency (e.g., USD), a target currency (e.g., JPY), and the amount they wish to convert.
  • Implement a check to ensure the API request was successful (status code 200) before attempting to parse the JSON.
  • Validate that the target currency exists in the returned rates dictionary. If it doesn't, print a user-friendly error message instead of letting the program crash with a KeyError.
  • Calculate and print the final converted amount formatted to two decimal places.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.