We have already seen how we can pass GET parameters in requests Python Flask. In this case we are going to see how we can force the type of parameters that are sent. That is, force the path of the parameters of a GET request to be of one type or another. In order to demonstrate how the parameters work Python Flask with type we are going to create a REST service that adds two numbers.
The first thing will be to install the Flask microframework.
pip install Flask
The next thing will be to create our Flask application.
from flask import Flask
app = Flask(__name__)
if __name__ == '__main__':
app.run(debug=True)
Now we are going to create the route that adds the numbers. This will be a path that has two variables and returns the sum of the two variables.
@app.route('/sum//',methods=['GET'])
def sum(s1,s2):
return str(s1+s2)
The problem with this path and addition method is that the parameters passed within the Path can be of any type and someone could invoke us in the following way:
/sum/hello/goodbye
And we would have something as curious as the two strings added “hello goodbye”.
What we are going to do is have parameters Python Flask with type, in this case we are going to force the parameters to be numbers. To do this we are going to indicate that the variables are of type int in the following way:
@app.route('/sum//',methods=['GET'])
def greeting(s1,s2):
return str(s1+s2)
This way our sum route will only be executed if the variables are integers. So we have seen how we can have parameters Python Typed Flask.
