Flask is a lightweight web framework, ideal for building simple web applications. Here’s a basic Python Flask API application written where we’re passing parameters in URL in different ways.
Table of Contents
1. Steps to create the Flask app:
- Install Flask using pip:
pip install Flask
- Create a new file, e.g.,
app.py
, and add the following code:
app.py
:
from flask import Flask
# Create a Flask instance
app = Flask(__name__)
# Define a route for the home page
@app.route('/')
def home():
return "Hello, Flask!"
# Run the app
if __name__ == '__main__':
app.run(debug=True)
Explanation:
- Flask instance (
app = Flask(__name__)
): Initializes the Flask application. @app.route('/')
: Defines the route for the home page (/
). When someone visits this URL, thehome
function will be called.app.run(debug=True)
: Runs the application in debug mode, which provides detailed error messages and automatically restarts the server on code changes.
Running the app:
- In the terminal, run: python app.py
- Open your browser and visit:
http://127.0.0.1:5000/
=> You should see: Hello, Flask!
In Flask, you can pass parameters to an API either through the URL path (path parameters) or via query strings (query parameters). Below are examples of both approaches.
2. Passing Parameters via URL Path (Path Parameters)
This is done by including placeholders in the route that will capture values from the URL.
Example:
from flask import Flask
app = Flask(__name__)
# Route with path parameter
@app.route('/greet/<name>')
def greet(name):
return f"Hello, {name}!"
if __name__ == '__main__':
app.run(debug=True)
How it works:
- The
/<name>
in the route captures the value from the URL. - When you visit
http://127.0.0.1:5000/greet/Alex
, it will respond with: Hello, Alex!
Summary:
- Path parameters are part of the URL path and are defined in the route.
3. Passing Parameters via Query Strings
Query parameters are passed after the ?
symbol in the URL, like ?param=value
.
Example:
from flask import Flask, request
app = Flask(__name__)
# Route with query parameters
@app.route('/greet')
def greet():
name = request.args.get('name', 'World') # Get 'name' parameter from query string
return f"Hello, {name}!"
if __name__ == '__main__':
app.run(debug=True)
How it works:
request.args.get('name')
: Fetches the value of the query parametername
. If no value is provided, it defaults to'World'
.- When you visit
http://127.0.0.1:5000/greet?name=Alex
, it will respond with: Hello, Alex! - If you visit without the query parameter (e.g.,
http://127.0.0.1:5000/greet
), it will respond with the default: Hello, World!
Summary:
- Query parameters are appended to the URL after a
?
and can be retrieved usingrequest.args
.
4. Passing Multiple Parameters via URL Path
In Flask, you can pass multiple parameters to an API via both URL path parameters and query string parameters. Here’s how you can handle multiple parameters with examples.
You can define multiple parameters in the URL path and access them in the view function.
Example:
from flask import Flask
app = Flask(__name__)
# Route with multiple path parameters
@app.route('/greet/<name>/<int:age>')
def greet(name, age):
return f"Hello, {name}! You are {age} years old."
if __name__ == '__main__':
app.run(debug=True)
How it works:
<name>
captures a string parameter.<int:age>
captures an integer parameter (you can specify the type withint
,float
, etc.).- When you visit
http://127.0.0.1:5000/greet/Alex/25
, it will respond with: Hello, Alex! You are 25 years old.
Summary:
- Multiple path parameters are defined in the route (e.g.,
/greet/<name>/<age>
).
5. Passing Multiple Parameters via Query Strings
You can pass multiple query parameters by appending them to the URL after ?
, separated by &
.
Example:
from flask import Flask, request
app = Flask(__name__)
# Route with multiple query parameters
@app.route('/greet')
def greet():
name = request.args.get('name', 'World') # Fetch the 'name' parameter
age = request.args.get('age', 'unknown') # Fetch the 'age' parameter
return f"Hello, {name}! You are {age} years old."
if __name__ == '__main__':
app.run(debug=True)
How it works:
request.args.get('name')
gets the value of thename
query parameter.request.args.get('age')
gets the value of theage
query parameter.- When you visit
http://127.0.0.1:5000/greet?name=Alex&age=25
, it will respond with: Hello, Alex! You are 25 years old. - If either parameter is missing, the default values (
'World'
forname
and'unknown'
forage
) will be used. For example, visitinghttp://127.0.0.1:5000/greet?name=Alex
would respond: Hello, Alex! You are unknown years old.
Summary:
- Multiple query parameters are passed after
?
, separated by&
(e.g.,?name=Alex&age=25
).
6. Passing a Mix of Path and Query Parameters
You can also combine both methods, passing some parameters via the URL path and others via the query string.
Example:
from flask import Flask, request
app = Flask(__name__)
# Route with path and query parameters
@app.route('/greet/<name>')
def greet(name):
age = request.args.get('age', 'unknown')
return f"Hello, {name}! You are {age} years old."
if __name__ == '__main__':
app.run(debug=True)
Here, the name
is passed via the URL path, and age
is passed as a query parameter.When you visit http://127.0.0.1:5000/greet/Alex?age=25
, it will respond: Hello, Alex! You are 25 years old.
Summary:
- You can mix and match path and query parameters as needed in your Flask app.
I hope this example helps. If you like my work then please like and comment on my post.