Published on January 26, 2024By DeveloperBreeze

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)

Comments

Please log in to leave a comment.

Continue Reading:

POST Request with Fetch API and JSON Data

Published on January 26, 2024

javascript

Promise-based Execution of Python Code with jsPython

Published on January 26, 2024

javascript

Simple Server-Side Handling of HTTP Methods

Published on January 26, 2024

php

Various cURL Examples for API Interactions

Published on January 26, 2024

bash

Tailwind Browser Mockup

Published on January 26, 2024

Simple and Clean Tailwind Buttons

Published on January 26, 2024

Tailwind Buttons with Arrow Icon

Published on January 26, 2024

Iconic Action Button Stack

Published on January 26, 2024

AI Interactive Chat Interface

Published on January 26, 2024

AI Chat Interface with Online Assistant

Published on January 26, 2024