Access URL Query Parameters in Flask

Flask – Access URL query parameters

In a flask application, we can access the URL query parameters using request object.

The following is a simple code snippet to access URL query parameter 'name' using request object.

request.args['name']

You may replace name with the key for any URL query parameter that you would like to access.

Please note that we need to import request from flask in order to access request object in our Python code.

Example

In this example, we build a flask application where we have following project structure.

Flask project structure

main.py

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/")
def home_page():
    name = request.args['name']
    return render_template("index.html", name=name)

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)

We read the value for URL parameter 'name' using the expression request.args['name'].

index.html

<!DOCTYPE html>
<html>
  <body>
    <h1>Hello {{name}}!</h1>
    <p>Welcome to sample flask application by <a href="https://pythonexamples.org/">PythonExamples.org</a>.</p>
  </body>
</html>

Run Application

Open terminal or command prompt at the root of the application, and run the Python file main.py.

Run Flask Application

The flask application is up and running at URL http://127.0.0.1:8080/.

Now, open a browser of your choice and hit the URL http://127.0.0.1:8080/?name=Tony.

Python Flask - Access URL query parameters

We have read the URL query parameter in the Python file, and passed it to the HTML template for display.

Project ZIP

Summary

In this Python Flask Tutorial, we learned how to access URL query parameter in Python file, with the help of an example flask application.

Related Tutorials

Code copied to clipboard successfully 👍