Predictive Hacks

How to Pass URL Variables to Flask API

flask_url_variables

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:

How to Pass URL Variables to Flask API 1

With Variables:

How to Pass URL Variables to Flask API 2

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

python package
Python

How to Build Python Packages

In this tutorial, we will show you how to build Python Packages. Our goal is to build a Python package