Extract parameters from URL in flask server

flask_url_variables

Skill - extract parameters from URL in flask server

Table of Contents

Skills Required

Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision


  • In this post we will learn how to extract parameters from URLs in flask server end-points
  • The URL parameters can be extracted from the URL path and URL query

extract variables from URL segments

from flask import Flask
from markupsafe import escape

app = Flask(__name__)

@app.route('/hello/<uname>')
def hello(uname):
    # uname variable extracted from url segment
    # sanitize the variable string using markupsafe
    sanitizedName = escape(uname)
    return "Hello {0}".format(sanitizedName)

@app.route('/echoNum/<int:num>')
def echoNum(num):
    # num integer variable is extracted from url segment
    return "The number was {0}".format(num)

@app.route('/echoPath/<path:pathVar>')
def echoPath(pathVar):
    # pathVar variable of type path is extracted from url segments
    return "The path was {0}".format(pathVar)

app.run(host='0.0.0.0', port=50100, debug=True)
  • int, float, path, uuid are the supported variable types that can be extracted from URL segments

extract variables from URL query parameters

  • using request.args imported from flask module, we can extract the query parameters from URL
  • using request.args.to_dict() function, we can get the URL query parameters as a python dict object
from flask import Flask, request
app = Flask(__name__)

@app.route('/search')
def search():
    # get the request query parameters as a python dict
    args = request.args.to_dict()

    # get the 'name' query parameter value with a default value as 'No Name'
    name = args.get("name", "No Name")

    return "Hello {0}!!!".format(name)

app.run(host='0.0.0.0', port=50100, debug=True)

Video

The video for this post can be seen here

References

Comments