In the previous article, the post and get API methods were presented. In this one, Put and Delete are coming. 🙂 Well, nothing that fancy, this is how these two methods look like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# Update item by id @app.route('/api/items/<int:item_id>', methods=['PUT']) def update_item(item_id): data = request.get_json() updated_data = data.get('item') # Get the nested 'item' data if not updated_data: return jsonify({'error': 'No data provided'}), 400 item = next((item for item in items if item['id'] == item_id), None) if item is None: return jsonify({'error': f'Item #{item_id} not found!'}) # Update fields in the item (dummy db) for key, value in updated_data.items(): if key in item: item[key] = value return jsonify({'message': 'Item updated successfully', 'item':item}), 200 # Delete item by id @app.route('/api/items/<int:item_id>', methods=['DELETE']) def delete_item(item_id): item_to_delete = next((item for item in items if item['id'] == item_id), None) if item_to_delete is None: return jsonify({'error': f'Item {item_id} not found!'}), 404 items.remove(item_to_delete) return jsonify({'message': f'Item: {item_to_delete} has been deleted successfully!'}), 200 |
And, of course tests are a…