currency-api icon indicating copy to clipboard operation
currency-api copied to clipboard

Include fallback mechanism in your code to avoid issues

Open fawazahmed0 opened this issue 2 years ago • 7 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

fawazahmed0 avatar Apr 23 '22 23:04 fawazahmed0

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?

SozinovD avatar Apr 04 '23 16:04 SozinovD

Yes please

fawazahmed0 avatar Apr 04 '23 18:04 fawazahmed0

Created a pull request with it

SozinovD avatar Apr 04 '23 19:04 SozinovD

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

SozinovD avatar Apr 04 '23 19:04 SozinovD

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')


fawazahmed0 avatar Apr 04 '23 20:04 fawazahmed0

Okay, as you wish

SozinovD avatar Apr 05 '23 04:04 SozinovD

@fawazahmed0 how do i go about changing the "usd/eur" to a users input instead? image

OskarKaz avatar Jan 18 '24 16:01 OskarKaz