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

Discover more amazing content handpicked just for you

Tutorial
javascript

Getting Started with Axios in JavaScript

axios.all([
    axios.get('https://jsonplaceholder.typicode.com/posts/1'),
    axios.get('https://jsonplaceholder.typicode.com/posts/2')
  ])
  .then(axios.spread((post1, post2) => {
    console.log('Post 1:', post1.data);
    console.log('Post 2:', post2.data);
  }))
  .catch(error => {
    console.error('Error fetching data:', error);
  });
  • We use axios.all() to send multiple requests.
  • The axios.spread() function is used to handle the responses separately.

Sep 02, 2024
Read More
Cheatsheet

REST API Cheatsheet: Comprehensive Guide with Examples

No preview available for this content.

Aug 24, 2024
Read More
Tutorial
go

Building a RESTful API with Go and Gorilla Mux

go run main.go

The server should be running on http://localhost:8000.

Aug 12, 2024
Read More
Tutorial
python

Creating a Simple REST API with Flask

from flask import Flask, jsonify, request, abort

app = Flask(__name__)

items = [
    {"id": 1, "name": "Item 1", "price": 100},
    {"id": 2, "name": "Item 2", "price": 150},
    {"id": 3, "name": "Item 3", "price": 200}
]

@app.route('/api/items', methods=['GET'])
def get_items():
    return jsonify(items)

@app.route('/api/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        abort(404)
    return jsonify(item)

@app.route('/api/items', methods=['POST'])
def create_item():
    if not request.json or 'name' not in request.json or 'price' not in request.json:
        abort(400)
    new_item = {
        "id": items[-1]['id'] + 1 if items else 1,
        "name": request.json['name'],
        "price": request.json['price']
    }
    items.append(new_item)
    return jsonify(new_item), 201

@app.route('/api/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        abort(404)
    if not request.json:
        abort(400)
    item['name'] = request.json.get('name', item['name'])
    item['price'] = request.json.get('price', item['price'])
    return jsonify(item)

@app.route('/api/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        abort(404)
    items.remove(item)
    return jsonify({"result": True})

if __name__ == '__main__':
    app.run(debug=True)

You can use Postman or curl to test the API.

Aug 03, 2024
Read More
Code
bash

Various cURL Examples for API Interactions

No preview available for this content.

Jan 26, 2024
Read More
Code
php

Simple Server-Side Handling of HTTP Methods

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!