Routes

Our application can say hello world now, but we’d like it to do more than that. We can map different functionality within our application to different URIs using routes.

You might remember from the last section that to see our application, you visited http://localhost:5000/. This is the base URL of our application. localhost is just a special alias for the IP address for your computer. The 5000 refers to the port the application is running on - generally websites run on port 80 or 443, and the port number is not shown in URLs, but when we’re developing on our local machines, other ports are often used and we have to explictly include them.

We can make our application respond to any path beyond the localhost:5000, for example http://localhost:5000/hello, or http://localhost:5000/hello/world. We do this using routes. Currently, our application has only one route.

Here’s our single route:

@app.route('/')
def hello():
    return "Hello world!"

In Flask, you define a route using the @app.route('/') syntax. The function directly after this line (called hello() in our example) will be run when a request is made to this route.

Our route is listening at the root URI of the application which is expressed as “/”, and so when we visit “http://localhost:5000/” our application will run the hello() function. If we wanted to create a route that could be accessed by visiting “http://localhost:5000/coolroute”, we’d define the route with @app.route('/coolroute'). We would then define a new function right after that would be run when a request is made to “/coolroute”.

Let’s add another route where we will eventually be able to see a generated poem:

@app.route('/poem')
def poem():
    return "A great poem will be here!"

So your full flask application will now look like this:

# app.py

from flask import Flask, render_template, redirect, url_for, jsonify

app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello world!"

@app.route('/poem')
def poem():
    return "A great poem will be here!"

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

Now visit: http://localhost:5000/poem

For more information on Flask routes see: https://pythonbasics.org/flask-tutorial-routes/