-3

I call an exchange API. When I try to put it as a function, it returns None:

def getCurrentExchange(source, target):
    """The function takes the source - source and target currency - target and extract the rate as of now"""
    url = 'https://api.exchangerate.host/convert?from=source&to=target'
    response = requests.get(url)
    data = response.json()
    xchng = data['result']
    return xchng 
print(getCurrentExchange("EUR", "USD"))

When I call the API without wrapping it as a function, I get the rate:

url = 'https://api.exchangerate.host/convert?from=USD&to=EUR'
response = requests.get(url)
data = response.json()
data['result']

What am I doing wrong?

eponkratova
  • 467
  • 7
  • 20
  • 3
    You need to add the line `return xchng` at the end of your function. Any function without a `return` statement will return `None` – C_Z_ Jan 11 '23 at 16:39
  • You aren't returning anything from your function, just printing. – takendarkk Jan 11 '23 at 16:39
  • Unfortunately, even if I add return xchng and then, wrap getCurrentExchange("EUR", "USD") to print(getCurrentExchange("EUR", "USD")), I would still get None – eponkratova Jan 11 '23 at 16:43
  • @eponkratova Update your code with a return in your function and request a re-open since it does not solve your issue – Jib Jan 11 '23 at 16:48
  • I think it has sth to do with the type - the rate is float. When I use the function, the returned type is NoneType , when I just call the API, the type is float. – eponkratova Jan 11 '23 at 16:56
  • 1
    @eponkratova This has to do with the URL you use in the function. You should use built-in string `format` to install value in your url: `"my_api_url = "https://api.exchangerate.host/convert?from={}&to={}".format(source, target)`. This will solve your issue – Jib Jan 11 '23 at 17:00
  • And indeed, it did solve the problem! Thank you, @Jib. I guess we cannot do anything with the closed status – eponkratova Jan 11 '23 at 17:02
  • @eponkratova I can't, indeed .. – Jib Jan 11 '23 at 17:05

1 Answers1

0

you need a return value.

def getCurrentExchange(source, target):
    """The function takes the source - source and target currency - target and extract the rate as of now"""
    url = f'https://api.exchangerate.host/convert?from={source}&to={target}'
    response = requests.get(url)
    data = response.json()
    return data['result']
getCurrentExchange("EUR", "USD")
samusa
  • 449
  • 2
  • 11
  • No, if I use def getCurrentExchange(source, target): """The function takes the source - source and target currency - target and extract the rate as of now""" url = 'https://api.exchangerate.host/convert?from=source&to=target' response = requests.get(url) data = response.json() xchng = data['result'] return xchng print(getCurrentExchange("EUR", "USD")) it still returns None – eponkratova Jan 11 '23 at 16:42
  • with f-strings you can fill your values into the url – samusa Jan 11 '23 at 16:47