Files
triviathang/backend/routes/categories.py
2025-12-22 14:47:25 -05:00

92 lines
2.6 KiB
Python

from flask import Blueprint, request, jsonify
from backend.models import db, Category
bp = Blueprint('categories', __name__, url_prefix='/api/categories')
@bp.route('', methods=['GET'])
def list_categories():
"""Get all categories"""
categories = Category.query.order_by(Category.name).all()
return jsonify([c.to_dict() for c in categories]), 200
@bp.route('/<int:category_id>', methods=['GET'])
def get_category(category_id):
"""Get a single category by ID"""
category = Category.query.get_or_404(category_id)
return jsonify(category.to_dict()), 200
@bp.route('', methods=['POST'])
def create_category():
"""Create a new category"""
data = request.get_json()
if not data:
return jsonify({'error': 'No data provided'}), 400
name = data.get('name', '').strip()
if not name:
return jsonify({'error': 'Category name is required'}), 400
# Check if category already exists
existing = Category.query.filter_by(name=name).first()
if existing:
return jsonify({'error': 'Category already exists'}), 409
try:
category = Category(name=name)
db.session.add(category)
db.session.commit()
return jsonify(category.to_dict()), 201
except Exception as e:
db.session.rollback()
return jsonify({'error': str(e)}), 500
@bp.route('/<int:category_id>', methods=['PUT'])
def update_category(category_id):
"""Update an existing category"""
category = Category.query.get_or_404(category_id)
data = request.get_json()
if not data:
return jsonify({'error': 'No data provided'}), 400
name = data.get('name', '').strip()
if not name:
return jsonify({'error': 'Category name is required'}), 400
# Check if another category with this name exists
existing = Category.query.filter(Category.name == name, Category.id != category_id).first()
if existing:
return jsonify({'error': 'Category already exists'}), 409
try:
category.name = name
db.session.commit()
return jsonify(category.to_dict()), 200
except Exception as e:
db.session.rollback()
return jsonify({'error': str(e)}), 500
@bp.route('/<int:category_id>', methods=['DELETE'])
def delete_category(category_id):
"""Delete a category"""
category = Category.query.get_or_404(category_id)
try:
db.session.delete(category)
db.session.commit()
return jsonify({'message': 'Category deleted successfully'}), 200
except Exception as e:
db.session.rollback()
return jsonify({'error': str(e)}), 500