I have the following python code:
JavaScript
x
7
1
import requests
2
3
def requestAPI(url):
4
return requests.get(url=url).json()
5
6
UselessFact = RequestApi("https://uselessfacts.jsph.pl/random.json?language=en")['text']
7
I wanted to put a try/except on the requestAPI
function so it does’nt break the code. I thought about this:
JavaScript
1
7
1
import requests
2
3
def requestAPI(url, keys):
4
return requests.get(url=url).json() #Here is the struggle with passing the "keys" parameter into the return
5
6
UselessFact = RequestApi("https://uselessfacts.jsph.pl/random.json?language=en", ['text'])
7
I could do something like:
JavaScript
1
11
11
1
import requests
2
3
def requestAPI(url):
4
try:
5
return requests.get(url=url).json()
6
7
except:
8
return False
9
10
UselessFact = RequestApi("https://uselessfacts.jsph.pl/random.json?language=en")['text'] if (condition here) else False
11
But i think there’s a better way of doing this.
Advertisement
Answer
You can achieve it without a try-except
via dict.get()
:
JavaScript
1
3
1
def requestAPI(url, key):
2
return requests.get(url=url).json().get(key, None)
3
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)
.