How Do You Write a Flask Program to Accept a Parameter in the URL?

Problem scenario
You want to pass a variable via a URL to a Python program. You want to use Flask for this. What do you do?

Solution
Prerequisite

Install Flask. If you need assistance, see this posting if you are using a CentOS/RHEL/Fedora server or this posting if you are using a Debian/Ubuntu server.

Procedures
This is a multi-route Flask program. Integers can be passed when the URL is called like this: curl http://127.0.0.1:5000/ccc/1

# The /ccc/ route below allows for integers to be passed.  The "ccc(var1)" function accepts a variable.

from flask import Flask, Response

app = Flask(__name__)


@app.route("/aaa")
def users():
    return Response("It works! Continually Integrate and Improve!"), 200

@app.route("/bbb")
def index():
    return Response("YYYYYYYYYYYYYYY"), 200

@app.route("/ccc/<int:var1>", strict_slashes=False)
def ccc(var1):
    return Response("the string entered is " + str(var1)), 200

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

Leave a comment

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