diff --git a/project/__init__.py b/project/__init__.py index 7cd395c..d2ba351 100755 --- a/project/__init__.py +++ b/project/__init__.py @@ -2,7 +2,7 @@ from flask import Flask, jsonify from flask_sqlalchemy import SQLAlchemy from database_singleton import Singleton -from project.api.views import test_blueprint +from project.api.views import request_blueprint # instantiate the app def create_app(script_info=None): @@ -19,7 +19,7 @@ def create_app(script_info=None): db.init_app(app) migrate.init_app(app, db) - app.register_blueprint(test_blueprint) + app.register_blueprint(request_blueprint) @app.shell_context_processor def ctx(): diff --git a/project/api/views.py b/project/api/views.py index a6e9eac..eda5323 100755 --- a/project/api/views.py +++ b/project/api/views.py @@ -3,15 +3,44 @@ from sqlalchemy import exc from project.api.models import Request -from project import db +from database_singleton import Singleton -test_blueprint = Blueprint("tasks", __name__) +request_blueprint = Blueprint("requests", __name__) +db = Singleton().database_connection() -@test_blueprint.route("/api/requests", methods=["GET"]) -def get_all_request(): - response = { - "status": "success", - "data": {"tasks": [request.to_json() for request in Request.query.all()]}, - } - return jsonify(response), 200 + +@request_blueprint.route("/requests", methods=["POST"]) +def create_request(): + post_data = request.get_json() + + error_response = {"status": "fail", "message": "Invalid payload."} + + productname = (post_data.get("productname"),) + startdate = (post_data.get("startdate"),) + enddate = (post_data.get("enddate"),) + description = (post_data.get("description"),) + requester = (post_data.get("requester"),) + productcategoryid = (post_data.get("productcategoryid"),) + lender = None + + lending_request = Request( + productname, + startdate, + enddate, + description, + requester, + lender, + productcategoryid, + ) + + try: + db.session.add(lending_request) + db.session.commit() + + response = {"status": "success", "data": {"request": lending_request.to_json()}} + + return jsonify(response), 201 + except exc.IntegrityError as e: + db.session.rollback() + return jsonify(error_response), 400