Cat facts with Python and API
codesharedot
Posted on October 21, 2019
Did you know you can get cat facts with Python?
There's a API for cat facts. Yes, really :)
An API lets you get data, it's a "data provider". They are used in almost every web app. This lets you practice with APIs and Python.
It has two end points
URL | what |
---|---|
/facts | Retrieve and query facts |
/users* | Get user data |
If you open the url https://cat-fact.herokuapp.com/facts you get all the facts in JSON data. An id would give only a single object.
So how to use that in Python?
This little program with requests will do it:
#!/usr/bin/python3
#_*_coding: utf-8_*_
import time
import json
import requests
data = requests.get('https://cat- fact.herokuapp.com/facts/58e0086f0aac31001185ed02')
print(data.json())
Get cat fact
What if you want only one fact?
You can add the id like this:
data = requests.get('https://cat-fact.herokuapp.com/facts/58e0086f0aac31001185ed02')
Then use the text attribute (see inside json object) to get the fact
#!/usr/bin/python3
#_*_coding: utf-8_*_
import time
import json
import requests
data = requests.get('https://cat-
fact.herokuapp.com/facts/58e0086f0aac31001185ed02')
print(data.json()['text'])
This is how you can interact with the API. Try it out on your own :)
Resources:
Posted on October 21, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.