I'd not actually used anything with json before, but (unsurprisingly) the requests library came through.
>>> import requests
>>> url = 'http://catfacts-api.appspot.com/api/facts?number=1'
>>> print(requests.get(url).json()['facts'][0])
Cat families usually play best in even numbers. Cats and kittens should be acquired in pairs whenever possible.
While that gets you the answer, when did you ever really just want the answer? That's pretty uninteresting. Let's get there in stages.
This is straightforward (yes, I'm assuming you have requests installed already):
>>> import requests
>>> url = 'http://catfacts-api.appspot.com/api/facts?number=1'
Then we can get the cat fact:
>>> cat_fact = requests.get(url)
Which looks like this:
>>> cat_fact.text
'{"facts": ["A cat\'s whiskers are thought to be a kind of radar, which helps a cat gauge the space it intends to walk through."], "success": "true"}'
Well, we really just want the string of the dictionary item in the string. The json() method makes it a dictionary, not a string.
>>> cat_fact.json()
{'facts': ["A cat's whiskers are thought to be a kind of radar, which helps a cat gauge the space it intends to walk through."], 'success': 'true'}
And we can use the dictionary key ('facts')...
>>> print(cat_fact.json()['facts'])
["A cat's whiskers are thought to be a kind of radar, which helps a cat gauge the space it intends to walk through."]
But we don't want a list, we want the string. So take the first item in the list.
>>> print(cat_fact.json()['facts'][0])
A cat's whiskers are thought to be a kind of radar, which helps a cat gauge the space it intends to walk through.
We could also iterate through a number of cat facts, including a spurious use of f-string formatting.
>>> number = 3
>>> url_number = f'http://catfacts-api.appspot.com/api/facts?number={number}'
>>> catfact = requests.get(url_number).json()
>>> catfact
{'facts': ['Not every cat gets "high" from catnip. Whether or not a cat responds to it depends upon a recessive gene: no gene, no joy.', 'Cats have an average of 24 whiskers, arranged in four horizontal rows on each side.', 'The strongest climber among the big cats, a leopard can carry prey twice its weight up a tree.'], 'success': 'true'}
>>> for fact in catfact['facts']:
... print(fact)
...
Not every cat gets "high" from catnip. Whether or not a cat responds to it depends upon a recessive gene: no gene, no joy.
Cats have an average of 24 whiskers, arranged in four horizontal rows on each side.
The strongest climber among the big cats, a leopard can carry prey twice its weight up a tree.
Which I think is quite enough about cat facts.
No comments:
Post a Comment