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.

Getting Started with Axios in JavaScript

This tutorial provides a comprehensive introduction to using Axios for making HTTP requests in JavaScript. By understanding these basics, you'll be able to integrate Axios into your applications, streamlining your API interactions and improving your development workflow.

Sep 02, 2024 Tutorial

Building a RESTful API with Go and Gorilla Mux

   mkdir booksapi
   cd booksapi

Aug 12, 2024 Tutorial

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!