0
0
Flaskframework~30 mins

Parameter type converters (int, float, path) in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Parameter Type Converters in Flask Routes
📖 Scenario: You are building a simple Flask web app that shows different pages based on URL parameters. You want to make sure the parameters are the right type so your app works smoothly.
🎯 Goal: Create Flask routes that use parameter type converters int, float, and path to handle URL parameters correctly.
📋 What You'll Learn
Create a Flask app instance named app
Add a route /item/<int:item_id> that accepts only integer item_id
Add a route /price/<float:price> that accepts only float price
Add a route /file/<path:filepath> that accepts a path string filepath
💡 Why This Matters
🌍 Real World
Web developers often need to get data from URLs and ensure it is the right type before using it. Flask's parameter type converters make this easy and reliable.
💼 Career
Understanding how to use Flask routes with typed parameters is essential for backend web development jobs that use Python and Flask frameworks.
Progress0 / 4 steps
1
Set up the Flask app and integer route
Import Flask from flask and create a Flask app instance called app. Then add a route /item/<int:item_id> that accepts an integer parameter called item_id. Inside the route function show_item, return a string showing the item ID using an f-string.
Flask
Need a hint?

Use @app.route('/item/<int:item_id>') to specify the integer parameter in the URL.

2
Add a route with a float parameter
Add a new route /price/<float:price> that accepts a float parameter called price. Define a function show_price that returns a string showing the price with two decimal places using an f-string.
Flask
Need a hint?

Use @app.route('/price/<float:price>') and format the float with {price:.2f} in the f-string.

3
Add a route with a path parameter
Add a route /file/<path:filepath> that accepts a path parameter called filepath. Define a function show_file that returns a string showing the file path.
Flask
Need a hint?

Use @app.route('/file/<path:filepath>') to accept a path parameter.

4
Add the app run command
Add the code to run the Flask app only if the script is run directly. Use app.run(debug=True) inside the if __name__ == '__main__': block.
Flask
Need a hint?

Use the standard Python check if __name__ == '__main__': to run the app.