DeveloperBreeze

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.

Flask Route Configuration with Optional Parameter Handling

Code January 26, 2024
python

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)