Hello Africoders and fellow computing students! This semester, Python has become my new playground, and as part of our coursework, our lecturer assigned us a group project. My group and I chose to create a practical and exciting project—a real-time currency converter. In this blog post, I’ll walk you through the steps we took to build this converter, from setting up the project and integrating an API, to overcoming various challenges that I encountered along the way.
Step 1: Creating the Project Folder
First, I created a new folder for my project and opened it in Visual Studio Code (VSCode). This is where I organized all the project files.
Step 2: Setting Up a Virtual Environment
To keep the project dependencies isolated and manageable, I created a virtual environment. Here’s how you can do it:
Open a terminal in VSCode.
Run the following command to create a virtual environment:
python -m venv venv
Activate the virtual environment:
On Windows:
`venv\Scripts\activate`
On macOS/Linux:
`source venv/bin/activate`
Step 3: Installing Necessary Libraries
I needed a couple of libraries to make the program work:
- requests: To handle HTTP requests to the CurrencyAPI.
- sys: To handle system-specific parameters and functions.
You can install requests using pip:
pip install requests
Getting the API Key
To get real-time currency exchange rates, I signed up on CurrencyAPI and obtained an API key. This key allows me to access the currency conversion data provided by the service.
Go to CurrencyAPI
Sign up for a free account
Once you have signed up, you will find your API key in the dashboard.
Understanding the Code Logic
My currency converter fetches exchange rates from the CurrencyAPI and calculates the converted amount based on user input. Here’s the pseudo-code for the program:
- Pseudo Code
- Define constants for the API key and base URL.
- Define a function to get the exchange rate
- Construct the API request URL
- Make a GET request to the API
- Parse the JSON response
- Return the exchange rate
- Define the main function
- Prompt the user for base currency, target currency, and amount.
- Call the exchange rate function.
- Calculate and print the converted amount.
- Run the main function if the script is executed directly.
The Code
Here’s the actual implementation of the program:
Code Explanation
Importing Libraries:
import sys
import requests
- requests is used to send HTTP requests to the CurrencyAPI.
- sys is used to handle system-specific functions, such as exiting the program.
Defining Constants:
API_KEY = 'YOUR_API_KEY'
BASE_URL = 'https://api.currencyapi.com/v3/latest'
- API_KEY is your personal API key from CurrencyAPI.
- BASE_URL is the endpoint for fetching the latest exchange rates.
Defining the get_exchange_rate Function
def get_exchange_rate(base_currency, target_currency):
url = f"{BASE_URL}?apikey={API_KEY}&base_currency={base_currency}¤cies={target_currency}"
try:
response = requests.get(url)
response.raise_for_status() # Check if request was successful
data = response.json()
if 'data' in data and target_currency in data['data']:
return data['data'][target_currency]['value']
else:
print(f"Invalid currency: {target_currency}")
sys.exit(1)
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
sys.exit(1)
Constructs the API request URL using the base currency and target currency.
Makes a GET request to the API.
Parses the JSON response and returns the exchange rate.
Defining the main Function:
def main():
base_currency = input("Enter the base currency (e.g., USD): ").strip().upper()
target_currency = input("Enter the target currency (e.g., EUR): ").strip().upper()
try:
amount = float(input("Enter the amount: "))
except ValueError:
print("Invalid amount. Please enter a numeric value.")
sys.exit(1)
rate = get_exchange_rate(base_currency, target_currency)
if rate is None:
print(f"Could not find exchange rate from {base_currency} to {target_currency}")
sys.exit(1)
converted_amount = amount * rate
print(f"{amount} {base_currency} is equivalent to {converted_amount:.2f} {target_currency}")
`
- Prompts the user for the base currency, target currency, and amount.
- Calls the get_exchange_ratefunction to get the exchange rate.
- Calculates and prints the converted amount.
Running the Main Function:
if __name__ == "__main__":
main()
Ensures that the main function is executed when the script is run directly.
Challenges and Solutions
1. No Internet Connection
Error: The program failed to fetch exchange rates due to lack of internet connectivity.
Solution: Added a try-except block to handle requests.exceptions.RequestException
and display an appropriate error message.
2. Invalid Currency Code
Error: Users entered incorrect or unsupported currency codes, causing the program to fail.
Solution: Added a check to ensure the target currency exists in the API response. If not, an error message is displayed, and the program exits gracefully.
3. Invalid Amount Input
Conclusion
This project was a fantastic learning experience for me. I learned how to interact with APIs, handle exceptions, and develop a user-friendly CLI application.
What do you think of my approach? Do you have any suggestions for improving the code? I’d love to hear your thoughts and ideas on how to make this project even better. Let’s keep coding and learning together!
Happy coding, Africoders and my fellow computing students!