-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
284: Practice Exercise: Building a Currency Converter Using a Live API
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
requestslibrary to fetch data fromhttps://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.
There are no comments for now.