Search code examples
pythonflaskerror-handlingflask-restful

How do I return an error message in Flask-resful?


I added a check on a Post method to only let appointments on different dates pass through but I don't know how to return an error msg. here's the code

from flask_restful import Resource, Api, request
from package.model import conn


class Appointments(Resource):

    def get(self):
        appointment = conn.execute("SELECT p.*,d.*,a.* from appointment a LEFT JOIN patient p ON a.pat_id = p.pat_id LEFT JOIN doctor d ON a.doc_id = d.doc_id ORDER BY appointment_date DESC").fetchall()
        return appointment

    def post(self):
        appointment = request.get_json(force=True)
        pat_id = appointment['pat_id']
        doc_id = appointment['doc_id']
        appointment_date = appointment['appointment_date']

        a = conn.execute("SELECT count(*) From appointment WHERE doc_id =?
         AND appointment_date=?",(doc_id,appointment_date,)).fetchone()
        if a['count(*)'] == 0:
            appointment['app_id'] = conn.execute('''INSERT INTO appointment(pat_id,doc_id,appointment_date)VALUES(?,?,?)''', (pat_id, doc_id,appointment_date)).lastrowid
            conn.commit()
            return appointment
        else:
            pass

what do I return instead of the pass statement?

PS: For context, I'm trying to improve https://github.com/tushariscoolster/HospitalManagementSystem


Solution

  • Flask-Restful provides an abort function, it's can raise an HTTPException with special HTTP code and message back to the client.

    So, you can try to change the code like below:

    from flask_restful import abort
    
    class Appointments(Resource):
        def post(self):
            # ignore some code
            if a['count(*)'] == 0:
               # ignore some code
            else:
               abort(403, error_message='just accept an appointment on special date')
    

    then, the client will receive 403 and a valid JSON string like below:

    {"error_message":"just accept an appointment on special date"}
    

    The last, the client should deal with the error message properly.