fawazahmed0 / currency-api

Free Currency Exchange Rates API with 150+ Currencies & No Rate Limits

Home Page:https://github.com/fawazahmed0/currency-api#readme

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Include fallback mechanism in your code to avoid issues

fawazahmed0 opened this issue · comments

This API have multiple fallback urls:

Fallback URL:

https://raw.githubusercontent.com/fawazahmed0/currency-api/{apiVersion}/{endpoint}

Pseudo code:
For example, if you want to fetch usd to eur rate:

Fetch https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/usd/eur.min.json
If above url fails, then try fetching https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/usd/eur.json
If above url fails, then try fetching https://raw.githubusercontent.com/fawazahmed0/currency-api/1/latest/currencies/usd/eur.min.json
If above url fails, then try fetching https://raw.githubusercontent.com/fawazahmed0/currency-api/1/latest/currencies/usd/eur.json

Man, i really love what you've done, this is awesome project!
Don't you mind if I post example of python library with such fallback mechanism that uses this project?

Yes please

Created a pull request with it

There is a mistake in comment, don't think it's much of a deal

I think it's better to share that code here for better visibility, no worries I will do that for you.

#!/usr/bin/env python3

# handler for free currency api made by SozinovD in 2023
# main project repo is here https://github.com/fawazahmed0/currency-api

import requests

base_urls_arr = []
base_urls_arr.append('https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/')
base_urls_arr.append('https://raw.githubusercontent.com/fawazahmed0/currency-api/1/')

suffix_arr = []
suffix_arr.append('.min.json')
suffix_arr.append('.json')

def get_rate(curr1, curr2, date):
  curr1 = curr1.lower()
  curr2 = curr2.lower()
  for base_url in base_urls_arr:
    for suff in suffix_arr:
      url = base_url + date + '/currencies/' + curr1 + '/' + curr2 + suff
      rate = requests.get(url)
      if rate.status_code == 200:
        break
    if rate.status_code == 200:
      break
  if rate.status_code != 200:
    return 'Not found'
  return rate.json()[curr2]

def get_today_rate(curr1, curr2):
  return get_rate(curr1, curr2, 'latest')

Okay, as you wish