Event-CRUD-Flask-python3-API/routes.py

61 lines
No EOL
1.9 KiB
Python

from flask import Blueprint, jsonify, request
from services import EventService
from middlewares import validate_event_post_request
api = Blueprint('api', __name__)
# Create new event
@api.route('/events', methods=['POST'])
@validate_event_post_request
def create_event():
try:
data = request.json
new_event = EventService.create_event(data)
if new_event:
return jsonify(new_event.to_dict()), 201
else:
return jsonify({'error': 'Failed to create event'}), 400
except Exception as e:
return jsonify({'error': str(e)}), 500
# Get All Events
@api.route('/events', methods=['GET'])
def get_events():
try:
return {"events": EventService.get_all_events()}, 200
except Exception as e:
return {"error": str(e)}, 500
# Get Event by ID
@api.route('/events/<int:event_id>', methods=['GET'])
def get_event(event_id):
try:
return {"event": EventService.get_event_by_id(event_id)}, 200
except Exception as e:
return {"error": str(e)}, 500
# Update Event
@api.route('/events/<int:event_id>', methods=['PUT'])
@validate_event_post_request
def update_event(event_id):
try:
data = request.json
updated_event = EventService.update_event(event_id, data)
if updated_event:
return jsonify(updated_event.to_dict()), 200
else:
return jsonify({'error': 'Failed to update event'}), 400
except Exception as e:
return jsonify({'error': str(e)}), 500
# DELETE Event
@api.route('/events/<int:event_id>', methods=['DELETE'])
def delete_event(event_id):
try:
deleted_event = EventService.delete_event(event_id)
if deleted_event:
return jsonify(deleted_event.to_dict()), 200
else:
return jsonify({'error': 'Failed to delete event'}), 400
except Exception as e:
return jsonify({'error': str(e)}), 500