import requests
API_KEY = 'YOUR_API_KEY'
response = requests.get(
'https://api.api-ninjas.com/v1/exchangerate',
params={'pair': 'USD_EUR'},
headers={'X-Api-Key': API_KEY},
)
print(response.json())Prerequisites
- Python 3.7+ installed
- The
requestslibrary (pip install requests) - A free API Ninjas API key
Step 1: Get your API key
Sign up at api-ninjas.com/register for a free API key.
Step 2: Make the API request
The endpoint expects a pair parameter formatted as BASE_QUOTE using ISO 4217 currency codes:
import requests
API_KEY = 'YOUR_API_KEY'
response = requests.get(
'https://api.api-ninjas.com/v1/exchangerate',
params={'pair': 'USD_EUR'},
headers={'X-Api-Key': API_KEY},
)
print(response.json())Step 3: Use the response
The API returns:
{
"currency_pair": "USD_EUR",
"exchange_rate": 0.9234
}To convert an amount, multiply by exchange_rate: amount * exchange_rate.
Complete example
A reusable converter function with environment-variable key and timeouts:
import os
import requests
API_KEY = os.environ['API_NINJAS_KEY']
URL = 'https://api.api-ninjas.com/v1/exchangerate'
def get_rate(base: str, quote: str) -> float:
response = requests.get(
URL,
params={'pair': f'{base}_{quote}'},
headers={'X-Api-Key': API_KEY},
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)
if __name__ == '__main__':
print(f"1 USD = {get_rate('USD', 'EUR'):.4f} EUR")
print(f"100 USD = {convert(100, 'USD', 'JPY'):.2f} JPY")Fetching multiple pairs
pairs = [('USD', 'EUR'), ('USD', 'GBP'), ('USD', 'JPY'), ('USD', 'CAD')]
for base, quote in pairs:
rate = get_rate(base, quote)
print(f"{base}/{quote}: {rate:.4f}")Error handling
from requests.exceptions import HTTPError
try:
rate = get_rate('USD', 'XYZ')
except HTTPError as e:
if e.response.status_code == 400:
print('Invalid currency pair')
elif e.response.status_code == 401:
print('Invalid or missing API key')
elif e.response.status_code == 429:
print('Rate limit exceeded')
else:
print(f'HTTP error: {e}')Related APIs
For currency-to-amount conversion in a single call, see the Convert Currency API. For cryptocurrency rates use Crypto Price.