🎓 A1Learner
🔍
0 of 50 lessons completed

Flask Query Strings

A query string adds named values to an address. It starts with a question mark after the path.

Make the app

This line imports Flask and request together. The route below reads the query string.

from flask import Flask, request

app = Flask(__name__)

Greet by name

The view reads name from the query string. World is the default when no name arrives.

@app.route("/greet")
def greet():
    name = request.args.get("name", "World")
    return "Hello, " + name + "!"

Ask with and without a name

The first address carries ?name=Bo. The second address carries no query string.

client = app.test_client()
print(client.get("/greet?name=Bo").data.decode())
print(client.get("/greet").data.decode())

Example

from flask import Flask, request

app = Flask(__name__)

@app.route("/greet")
def greet():
    name = request.args.get("name", "World")
    return "Hello, " + name + "!"

client = app.test_client()
print(client.get("/greet?name=Bo").data.decode())
print(client.get("/greet").data.decode())

Key points

  • ?name=Ana adds the value Ana under the name name.
  • request.args holds the query values.
  • args.get("name", "World") returns World when name is missing.
  • Use query strings for optional choices, like a name.

In this example, the view reads name from request.args. The default is World. The test client asks once with ?name=Bo and once with no query string. The prints show the greeting for each ask.

Note

Values in a query string are always text.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does request.args.get("name", "World") return for /greet with no query string?