NewConnect Claude, Gemini, ChatGPT, and other AI agents to API Ninjas via our MCP server

How to Get Exchange Rates in Python

Exchange Rate APIUpdated August 28, 2026
Create a free API key and it will be pre-filled into every code sample on this page. No credit card required.
Getting a currency exchange rate in Python takes one GET request to the Exchange Rate API with a pair like USD_EUR — the response is the live mid-market rate. This guide covers the request, converting amounts with the rate, and the small hardening details that make the code safe to ship.

Prerequisites

You need three things:

  • Python 3.8 or newer.
  • The requests library.
  • A free API Ninjas API key — issued instantly, no credit card. If you already have an account, it's on your profile page.
shell
pip install requests

Step 1: Fetch your first rate

The endpoint is /v1/exchangerate and takes one parameter: pair, formatted as BASE_QUOTE with ISO 4217 currency codes.

fx.py
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 EUR

Here is the request on the wire and the full response:

api.api-ninjas.com
GET/v1/exchangerate?pair=USD_EUR
200 OKapplication/json
{ "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:

convert.py
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 EUR

If 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:

fx_client.py
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.py
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:

errors.py
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.

fx_rates.py

The complete script from this guide: session reuse, rate lookup, and a command-line pair list.

Frequently asked questions

What currencies are supported?

The API supports 150+ fiat currencies using standard ISO 4217 codes — USD, EUR, JPY, GBP, and so on. Format the pair parameter as BASE_QUOTE, for example USD_EUR.

How fresh are the exchange rates?

Rates are updated continuously from interbank foreign-exchange markets and reflect the latest published mid-market rate.

How do I convert an amount instead of fetching a rate?

Multiply your amount by the exchange_rate field, or call the Convert Currency API, which takes an amount plus the two currencies and returns the converted value in one request.

Can I get historical exchange rates?

This endpoint returns the current rate. For historical series, see the Exchange Rate API documentation for the historical endpoint options.

Can I convert cryptocurrency with this API?

No — use the dedicated Crypto Price API for crypto-to-fiat and crypto-to-crypto rates.