0
0
Flaskframework~5 mins

Parameter type converters (int, float, path) in Flask

Choose your learning style9 modes available
Introduction

Parameter type converters help Flask understand what kind of data to expect in a URL. This makes your app more reliable and clear.

When you want to get a number from the URL and use it as an integer.
When you need to accept decimal numbers from the URL.
When you want to capture a full file path or folder path from the URL.
Syntax
Flask
@app.route('/item/<int:item_id>')
def function_name(item_id):
    pass

The part inside <> is the variable name and type.

Common types are int, float, and path.

Examples
This route only accepts integer user IDs.
Flask
@app.route('/user/<int:user_id>')
def show_user(user_id):
    return f"User ID is {user_id}"
This route accepts decimal numbers like 12.99.
Flask
@app.route('/price/<float:amount>')
def show_price(amount):
    return f"Price is {amount}"
This route accepts a full path, including slashes.
Flask
@app.route('/files/<path:filename>')
def show_file(filename):
    return f"File path is {filename}"
Sample Program

This Flask app has three routes. Each uses a different type converter to get data from the URL and show it back.

Flask
from flask import Flask
app = Flask(__name__)

@app.route('/item/<int:item_id>')
def item(item_id):
    return f"Item number: {item_id}"

@app.route('/cost/<float:cost>')
def cost_route(cost):
    return f"Cost is: {cost}"

@app.route('/path/<path:subpath>')
def path(subpath):
    return f"Subpath is: {subpath}"

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

If the URL part does not match the type, Flask returns a 404 error.

The path converter allows slashes, unlike string.

Use type converters to avoid manual data checks inside your functions.

Summary

Parameter type converters tell Flask what kind of data to expect in URLs.

Common converters are int, float, and path.

They help make your routes clear and your app safer.