Open In App

How to Handle Missing Parameters in URL with Flask

Last Updated : 23 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to handle missing parameters in URLs with Flask. It is a web framework that offers libraries for creating simple web applications in Python. In Flask, URL parameters, commonly referred to as “query strings,” you can organize extra information for a certain URL. Parameters are added to the end of a URL after a ‘?’ symbol and additional parameters can be added by separating them with the “&” symbol. An illustration of a URL containing URL parameters is represented below:

Handle Missing Parameters in URL with Flask

 

Steps to Handle Missing Parameters in URL with Flask

Sometimes, there can be parameters that the endpoints expect in the URL string but aren’t included. We will look at how to deal with such cases using the try-except block and a recommended way of using the get() method. 

We will follow the below steps in both methods:

  1. Extract the arguments or parameters from the URL string.
  2. Retrieve the parameters which are present.
  3. Handle the parameters which are not present.
  4. Return the response containing these parameters.

You can install Flask using the below command:

pip install flask

Handle Missing Parameters in URL with Flask using try-except 

In the code, we have imported the request method from the Flask module. The method has an attribute named args which extracts all the arguments within a URL parameter and provides it as an ImmutableDict object. This can be converted to a Python dict type by simply applying the dict() method.  Then access the items using key names in square brackets, and we get the value of the item if the item is present. But in cases where the item does not exist in the ImmutableDict, it will throw a KeyError. 

Here, We are trying to access the URL “http://127.0.0.1:5000/profile?userid=12009&name=amit” where userid and name are present but contact is not available as a parameter key. Therefore, to access the contact key name, we have used to try-except block where we are trying to catch the KeyError and assign the contact as None if not found in the URL parameters. 

Python3




# Importing required functions
from flask import Flask, request
  
# Flask constructor
app = Flask(__name__)
  
# Root endpoint
  
  
@app.route('/profile')
def profile():
    # Extract the URL parameters
    url_params = request.args
  
    # Retrieve parameters which are present
    user_id = url_params['userid']
    username = url_params['name']
  
    # Retrieve parameters that is not present
    try:
        contact = url_params['contact']
    except KeyError:
        contact = None
  
    # Return the components to the HTML template
    return {
        'userId': user_id,
        'userName': username,
        'userContact': contact
    }
  
# Main Driver Function
if __name__ == '__main__':
    # Run the application on the local development server
    app.run(debug=True)


Output:

The output of this program can be viewed using the same link – “http://127.0.0.1:5000/profile?userid=12009&name=amit“.

Handle Missing Parameters in URL with Flask

 

Note: Please note that the output window may look different as I have installed a JSON beautifier add-on in my browser. However, you shall be able to view the JSON response in raw format if the code runs successfully.

Handle Missing Parameters in URL with Flask

 

Handle Missing Parameters in URL with Flask using get() method

The problem with using try-except is that you should have prior information about the presence of a key-value pair in the URL parameters. Otherwise, you need to write try-except to extract every pair, which is not a good approach. 
In this example, we are trying to access the key names using the get() method. The advantage of using this method is that, in cases where the key name is not found, it assigns a None value by default (contrary to throwing KeyError while using square brackets for access). We can also provide a default value if we do not wish to assign None.  As shown in the example, the second parameter of the get() method is ‘NA’ which replaces the default value. 
 

Python3




# Importing required functions 
from flask import Flask, request
  
# Flask constructor 
app = Flask(__name__)
  
# Root endpoint 
  
  
@app.route('/profile')
def profile():
  
    # Extract the URL parameters 
    url_params = request.args
  
    # Retrieve parameters using get() 
    user_id = url_params.get('userid')
    username = url_params.get('name')
    # If contact is not present then 'NA' will be the default value
    contact = url_params.get('contact', 'NA')
  
    # Return the components to the HTML template 
    return {
        'userId': user_id,
        'userName': username,
        'userContact': contact
    }
  
  
# Main Driver Function 
if __name__ == '__main__':
    # Run the application on the local development server 
    app.run(debug=True)


Output:

The output of this program can be viewed using the same link – “http://127.0.0.1:5000/profile?userid=12009&name=amit“.

Handle Missing Parameters in URL with Flask

Output – Example 2 – GIF

Note: Please note that the output window may look different as I have installed a JSON beautifier add-on in my browser. However, you shall be able to view the JSON response in raw format if the code runs successfully.

Handle Missing Parameters in URL with Flask

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads