When we are creating our routes in Flask it is very likely that we will need to pass parameters. What we are going to see in this example is how we can pass parameters in routes Python Flask.
The first thing will have been to install the Flask microframework.
pip install Flask
And having created our Flask application.
from flask import Flask
app = Flask(__name__)
if __name__ == '__main__':
app.run()
Now we are going to create a route, which receives a name as a parameter and returns a response message in the form of a greeting, “Hello” and the name sent. This will help us see how we can pass parameters in routes Python Flask.
The first thing is to focus on the route.
@app.route('/greeting/',methods=['GET'])
The route must indicate the name of the variable that will be obtained from the URI using a name inside the minus and greater symbols. Also, in this case, we have indicated that the request method is a GET type.
Now we are going to define a method that addresses this route. The peculiarity of said method will be that it must have a parameter, which will correspond to the route variable.
def greeting(name):
return 'Hello ' + name + '!!!'
Now we can use this variable within the method. In our case we have used it in the response as part of the greeting.
Finally, the entire route will look like this:
@app.route('/greeting/',methods=['GET'])
def greeting(name):
return 'Hello ' + name + '!!!'
We have already seen how easy it is to pass parameters in routes Python Flask.
