Reading a quote daily may boost you in different aspects. But, it will take time to surf the internet every day for quotes. So, how to save time? We can automate that repeated process using Python.
Here, we are going to write a program that fetches a random quote without searching the internet.
Before moving further, we need to install a package called requests to make API calls. Install it using the following command.
pip install requests
Let’s see how to get the random quote.
Getting Random Quote
We are going to use the Quote Garden API to get a random quote. The API to get the random quote is here.
We have got the API. Now, it’s time to write code to get the random quote. See the code below.
## function that gets the random quote
## making the get request
response = requests.get("https://api-ninjas.com/api/quotes")
if response.status_code == 200:
## extracting the core data
json_data = response.json()
data = json_data['data']
## getting the quote from the data
print("Error while getting quote")
print("Something went wrong! Try Again!")
There is no need to explain the code as it is self-explanatory. You can print out the JSON data to see the complete data structure.
Note: the API response data structure may update in the future. So, make sure you are extracting the data correctly.
We have successfully got the random quote using Python. Can we improve it a bit further? Yes, we can always. You may set up a cron job to get the quote daily at a particular time and store it somewhere to read. That’s cool. If you set up the cron job, you don’t even have to run the script every day to read a quote :).
If you got to here, then you probably got the quote of the day. But, don’t stop it here. Go beyond it. You may create a wallpaper with a random quote and set it up as Desktop wallpaper. So every day, there will be something new to boost you.
That’s not all. There are many things you may do after getting a random quote. Some of them send the quote to your friends and family on WhatsApp, update the status on social media handles, post them on social media handles, etc… There are no limits to what you can do with it.
Next, build a tic-tac-toe game in Python or learn about List Comprehensions in Python?
Happy Coding! 💻