Prerequisites
You need three things:
- Python 3.8 or newer.
- The
requestslibrary. - A free API Ninjas API key — issued instantly, no credit card. If you already have an account, it's on your profile page.
pip install requestsStep 1: Fetch your first rate
The endpoint is /v1/exchangerate and takes one parameter: pair, formatted as BASE_QUOTE with ISO 4217 currency codes.
import requests
response = requests.get(
'https://api.api-ninjas.com/v1/exchangerate',
params={'pair': 'USD_EUR'},
headers={'X-Api-Key': 'YOUR_API_KEY'},
timeout=10,
)
response.raise_for_status()
data = response.json()
print(f"1 USD = {data['exchange_rate']} EUR")
# 1 USD = 0.9234 EURHere is the request on the wire and the full response:
{
"currency_pair": "USD_EUR",
"exchange_rate": 0.9234
}Two fields, no surprises: the pair you asked for, and the current mid-market rate.
Step 2: Convert an amount
The rate is a multiplier. To convert an amount of the base currency into the quote currency, multiply:
def convert(amount: float, rate: float) -> float:
return amount * rate
rate = data['exchange_rate']
print(f"250 USD = {convert(250, rate):.2f} EUR")
# 250 USD = 230.85 EURIf conversion is all you need, the Convert Currency API does it in a single call — pass the amount and both currencies, get the converted value back.
Step 3: Harden the client
Before this code runs anywhere real, fix the two usual weaknesses: move the key out of the source and into an environment variable, and reuse one connection instead of opening a new one per request. Wrapped as functions, the client looks like this:
import os
import requests
API_URL = 'https://api.api-ninjas.com/v1/exchangerate'
session = requests.Session()
session.headers['X-Api-Key'] = os.environ.get('API_NINJAS_KEY', 'YOUR_API_KEY')
def get_rate(base: str, quote: str) -> float:
"""Return the mid-market rate for one currency pair."""
response = session.get(
API_URL,
params={'pair': f'{base}_{quote}'},
timeout=10,
)
response.raise_for_status()
return response.json()['exchange_rate']
def convert(amount: float, base: str, quote: str) -> float:
return amount * get_rate(base, quote)
print(f"1 USD = {get_rate('USD', 'EUR'):.4f} EUR")
print(f"100 USD = {convert(100, 'USD', 'JPY'):.2f} JPY")Run export API_NINJAS_KEY=your_key once in your shell and the script never contains a secret. get_rate() is the building block the rest of this guide uses.
Step 4: Fetch multiple pairs
A currency dashboard is a loop over pairs. Because the session reuses its connection, a batch of lookups stays fast:
pairs = [('USD', 'EUR'), ('USD', 'GBP'), ('USD', 'JPY'), ('EUR', 'CHF')]
for base, quote in pairs:
print(f"{base}/{quote}: {get_rate(base, quote):.4f}")Step 5: Handle errors
The failures you'll actually see: a bad currency code (400), a missing key (401), and the rate limit (429). Catch them explicitly so each produces a useful message:
from requests.exceptions import HTTPError, RequestException
try:
rate = get_rate('USD', 'XYZ')
except HTTPError as error:
status = error.response.status_code
if status == 400:
print('Invalid currency pair — check both ISO 4217 codes')
elif status == 401:
print('Missing or invalid API key')
elif status == 429:
print('Rate limit exceeded — slow down and retry')
else:
print(f'HTTP {status}: {error.response.text}')
except RequestException as error:
print(f'Network error: {error}')Where to go from here
The same key covers the neighboring use cases: the Convert Currency API for one-call amount conversion, and the Crypto Price API when the pair involves Bitcoin instead of euros. Or grab the complete script below.