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: