How to build a Flask Joke Generator

flask jokes app flask basic app flask simple app

In this tutorial, we will be building a flask app that generates jokes. We will be implementing it using the chuck Norris free API.

Disclaimer Dry jokes ahead from the API.

To begin we will be using the flask library as our web development framework and requests library to make HTTP requests.

To install the above libraries run the commands below.

pip3 install flask 
pip3 install requests

Now let’s create a folder called flask-chuck, you can call it anything. Inside the folder create a file called app.py. Also, create a folder called templates and insert called index.html.

Now we need to import some modules in our app.py file. To do so add the following in the app.py file.

from flask import Flask,render_template

import requests

Next, we need to initialize our app. Add the following.

app = Flask(__name__)

Let’s now create our route and function.

@app.route('/')
def index():
    url = "https://api.chucknorris.io/jokes/random"
    response = requests.get(url)
    joke = response.json()['value']
    return render_template('index.html',joke=joke)

The above function requests a joke from the chuck Norris API and then rendered it to the html template,

Now let’s add the code below to finish the app.py file.

if __name__ == "__main__":
    app.run(debug=True)
    

Now let’s create our template to present the information. In the index.html add the following.

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      background-color: #333;
      color: #fff;
      text-align: center;
    }
  </style>
</head>
<body>
  <h1>Chuck Norris Jokes</h1>
  <p>{{ joke }}</p>
</body>
</html>

The above template presents the joke and displays it to your browser.

To start the server run the command below.

python3 app.py

You can also use the command below.

flask run

Now open your browser and enter the address below.

http://127.0.0.1:5000

You can now see a random joke displayed as shown below.

There you have it. Thanks for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *