How can I get the named parameters from a URL using Flask?

Naveera A.

The Problem

How can I get the named parameters from a URL using Flask?

The Solution

Flask provides a global request object that contains all sorts of information about the current HTTP request. Flask also parses the incoming request data for you.

You can use the args property of this global request object to get the values of query parameters.

For example, to access the query parameters of the following URL:

You can use the get method on request.args, like so:

# import main Flask class and request object from flask import Flask, request # create the Flask app app = Flask(__name__) @app.route('/query_example') def query_example(): language = request.args.get('language') framework = request.args.get('framework') print(f'language: {language}, framework: {framework}') return 'Query Parameters Example' if __name__ == '__main__':, port=5000)

You will get:

language: Python, framework: Flask

The request.args attribute is an ImmutableMultiDict that implements all standard dictionary methods.

The get method also takes optional arguments for default value and type. The following example should explain this behavior:

def query_example(): language = request.args.get('language', default='Python') framework = request.args.get('framework', default='Flask')

For /query_example?language=JavaScript:

language: JavaScript, framework: Flask

For /query_example:

language: Python, framework: Flask

For /query_example?language=JavaScript&framework=Express:

language: JavaScript, framework: Express

For /query_example?framework=Express:

language: Python, framework: Express

Further Reading

How do you access the query string in Flask routes?

Join the discussionCome work with us
Share on Twitter
Bookmark this page
Ask a questionImprove this Answer

Related Answers

A better experience for your users. An easier life for your developers.

© 2023 • Sentry is a registered Trademark
of Functional Software, Inc.