Sentry Answers>Flask>

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

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

Naveera A.

The ProblemJump To Solution

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:

http://mysite.com/query_example?language=Python&framework=Flask

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

Click to Copy
# 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__': app.run(debug=True, port=5000)

You will get:

Click to Copy
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:

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

For /query_example?language=JavaScript:

Click to Copy
language: JavaScript, framework: Flask

For /query_example:

Click to Copy
language: Python, framework: Flask

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

Click to Copy
language: JavaScript, framework: Express

For /query_example?framework=Express:

Click to Copy
language: Python, framework: Express

Further Reading

How do you access the query string in Flask routes?

  • SentryFlask Error Monitoring
  • Community SeriesIdentify, Trace, and Fix Endpoint Regression Issues
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty Treats for Web Developers brought to you by Sentry. Web development tips and tricks hosted by Wes Bos and Scott Tolinski

    Listen to Syntax

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

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