1

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

I knew it could be better! Thank you!
How could i do it with multiple keys? (An array of them)
You can check this answer, or the other ones.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.