Skip to content
Advertisement

Python pass array into function and use it in json return

I have the following python code:

import requests

def requestAPI(url):
  return requests.get(url=url).json()

UselessFact = RequestApi("https://uselessfacts.jsph.pl/random.json?language=en")['text']

I wanted to put a try/except on the requestAPI function so it does’nt break the code. I thought about this:

import requests

def requestAPI(url, keys):
  return requests.get(url=url).json() #Here is the struggle with passing the "keys" parameter into the return

UselessFact = RequestApi("https://uselessfacts.jsph.pl/random.json?language=en", ['text'])

I could do something like:

import requests

def requestAPI(url):
  try:
    return requests.get(url=url).json() 

  except:
    return False

UselessFact = RequestApi("https://uselessfacts.jsph.pl/random.json?language=en")['text'] if (condition here) else False

But i think there’s a better way of doing this.

Advertisement

Answer

You can achieve it without a try-except via dict.get():

def requestAPI(url, key):
    return requests.get(url=url).json().get(key, None)

This will return the value for key key if it exists in the JSON otherwise it will return None. If you want it to return False, do .get(key, False).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement