in

How to Generate a Random Quote Using Python

default image

Hey friend! Looking for a bit of inspiration? Random quotes can be a great way to find uplifting and thought-provoking ideas. Let‘s look at how to create your own automatic quote generator with Python.

As a fellow coding geek and data nerd, I love building little tools like this. So I wanted to share a fun programming project for getting randomized quotes from APIs and delivering them right to your inbox!

Why Have an Automated Quote Generator?

Here are some of the advantages of having quotes fetched and sent automatically:

  • Provides a regular dose of motivation without effort
  • Exposure to many perspectives from different authors
  • Discover new inspiring quotes you haven‘t seen before
  • Faster than manually searching for quotes
  • Easy to customize to your interests and schedule

Let‘s look at a few examples of how automated quotes can be useful:

  • Inspirational quote emailed as you start your workday
  • Random quote texted to you as an afternoon pick-me-up
  • Fortune cookie style quote at the end of your code commits
  • New quote automatically posted to your Twitter/Facebook daily

So let‘s dive in and see how to build your own!

Helpful Python Modules

To fetch quotes from APIs and handle scheduling, we‘ll need the following Python modules:

requests – Makes HTTP requests to access quote REST APIs
random – Selects random quotes from the API response data
time – Can pause code execution for scheduling
sqlite3 – Saves quotes to a local database file

We‘ll import these at the top:

import requests
import random 
import time
import sqlite3

Now we‘re ready to start pulling in quotes!

Sources for Quotes APIs

There are a few free APIs available with large databases we can access:

We could also build a scraper for sites like Goodreads, but these APIs provide easy quotation data.

I‘ll show examples using the QuoteGarden API, but you can experiment with any quote source.

Fetching a Random Quote

The QuoteGarden API endpoint for getting random quotes is here:

https://quote-garden.herokuapp.com/api/v3/quotes/random

Let‘s make a get_quote() function to fetch from this API:

import requests

def get_quote():
  response = requests.get("https://quote-garden.herokuapp.com/api/v3/quotes/random")

  if response.status_code == 200:
    json_data = response.json()
    quote_data = json_data[‘data‘]
    quote = quote_data[0][‘quoteText‘]
    print(quote)
  else:
    print("Error fetching quote")

We use the requests module to make a GET call to the API URL. This returns a Response object we can convert to JSON to access our quote text.

This will print a new random quote each time we call this function!

Handling Errors

We should also include some error handling:

import requests

def get_quote():
  try:
    response = requests.get("https://quote-garden.herokuapp.com/api/v3/quotes/random")

    if response.status_code == 200:  
      json_data = response.json()
      quote_data = json_data[‘data‘]  
      quote = quote_data[0][‘quoteText‘]
      print(quote)

    else:
      print("Error fetching quote")

  except Exception as e:
    print(f"Error: {e}")

This will catch any exceptions when calling the API.

Storing Quotes

To save our quotes, we can use a SQLite database. First we‘ll create a table to store them:

import sqlite3

db = sqlite3.connect(‘quotes.db‘)

db.execute(‘‘‘
  CREATE TABLE quotes (
    id INTEGER PRIMARY KEY,
    quote TEXT NOT NULL
  );
‘‘‘)

Then we can insert quotes after fetching them:

def save_quote(quote):
  db.execute("""
    INSERT INTO quotes (quote) VALUES (?)
  """, (quote,))

  db.commit()

Now we can save each quote and build up a collection!

Scheduling the Quote Script

To have quotes fetched at regular intervals, we can schedule the script using cron (Linux/Mac) or Windows Task Scheduler.

Some examples crontab entry variations:

# Run at 10am daily
0 10 * * * python /quotes.py

# Run every hour  
0 * * * * python /quotes.py

# Run every 15 mins
*/15 * * * * python /quotes.py 

This allows the script to run automatically in the background!

Formatting and Sharing Quotes

Once we have a nice database of quotes, we can start formatting them for emails, texts, social media etc.

Some ideas:

  • Randomly select a quote and email to yourself each morning
  • Text yourself a short afternoon quote with quote bot APIs like Twilio
  • Post a quote image to Twitter/Facebook feeds daily

The options are endless! Feel free to customize it and make it your own.

Conclusion

Being able to generate randomized quotes on demand is a great coding project! We learned how to:

  • Access free quote APIs with Python
  • Store quotes in a database
  • Schedule automatic quote fetching
  • Share quotes across various mediums

Hopefully this gives you some ideas to build your own bot for delivering inspiring quotes! Let me know if you end up creating something cool with this. Happy coding!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.