Skip to content

Handling Query Parameters

Query parameters are the ?key=value part of a URL.

Example:

  • /search?q=flask&page=2
diagram query parameters are strings, and missing is not an error mermaid
Everything in a query string arrives as text. request.args.get returns None for a key that is absent rather than raising, so a typo in the parameter name looks exactly like a user who did not supply it. Asking for a type converts the value -- and, importantly, also returns None when the conversion fails.

Flask stores query parameters in request.args.

python
from flask import Flask, request
 
app = Flask(__name__)
 
 
@app.route("/search")
def search():
    q = request.args.get("q", "")
    page = request.args.get("page", default=1, type=int)
    return {"q": q, "page": page}
  • Converts the string to the type you expect
  • If conversion fails, Flask returns the default (instead of crashing)

Some URLs have repeated params:

  • /filter?tag=python&tag=flask
python
tags = request.args.getlist("tag")

Even with type=int, you still should validate:

  • ranges (page >= 1)
  • allowed values (sort in top)

If invalid, return a clear error or a 400 status code.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading