Flask Programming Tutorials, Guides & Best Practices
Explore 1+ expertly crafted flask tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.
Adblocker Detected
It looks like you're using an adblocker. Our website relies on ads to keep running. Please consider disabling your adblocker to support us and access the content.
Code
python
Flask Route Configuration with Optional Parameter Handling
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/url", defaults={'param': None}, methods=["GET", "POST"])
@app.route("/url/<param>", methods=["GET", "POST"])
def url_route(param):
"""
Handle both GET and POST requests for the /url and /url/<param> endpoints.
- When accessed as /url, 'param' will be None.
- When accessed as /url/<param>, 'param' will contain the given value.
On a GET request, return a JSON response indicating the param state.
On a POST request, echo back any JSON data sent by the client.
"""
if request.method == "GET":
response = {
"message": "GET request received",
"param": param if param is not None else "No parameter provided"
}
return jsonify(response), 200
if request.method == "POST":
# Assume incoming data is JSON. If not, handle exceptions as needed.
data = request.get_json(silent=True) or {}
response = {
"message": "POST request received",
"param": param if param is not None else "No parameter provided",
"data_received": data
}
return jsonify(response), 201
if __name__ == "__main__":
app.run(debug=True)Jan 26, 2024
Read More