DeveloperBreeze

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)

Continue Reading

Handpicked posts just for you — based on your current read.

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!