How to Pass URL Variables to Flask API
[This article was first published on Python – Predictive Hacks, and kindly contributed to python-bloggers]. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.
Want to share your content on python-bloggers? click here.
We will show how you can build a flask API that gets URL variables. Recall that when we would like to pass a parameter to the URL we use the following syntax:
Assume that we want to pass the name
and the age
. Then the URL will be:
http://127.0.0.1:5000?name=Sergio&age=40
We will provide an example of how we can pass URL variables and the URL will be:
http://127.0.0.1:5000/Sergio/40
Let’s provide the code of the Flask API with these two cases:
from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/with_parameters') def with_parameters(): name = request.args.get('name') age = int(request.args.get('age')) return jsonify(message="My name is " + name + " and I am " + str(age) + " years old") @app.route('/with_url_variables/<string:name>/<int:age>') def with_url_variables(name: str, age: int): return jsonify(message="My name is " + name + " and I am " + str(age) + " years old") if __name__ == '__main__': app.run()
Let’s see the GET requests in Postman.
With Parameters:

With Variables:

To leave a comment for the author, please follow the link and comment on their blog: Python – Predictive Hacks.
Want to share your content on python-bloggers? click here.