I am trying to create an error handler in my Flask API such that when an empty body is sent in a post request, the response should generate a jsonified 400 error message and give the status code as 400 Bad Request on Postman. But currently I am getting 400 error message in the response body and 500 status code on Postman [1]: https://i.stack.imgur.com/DV1BX.png
import pyodbc
from pytz import timezone
from flask import Flask, jsonify, request, Response
from datetime import datetime, timedelta
from waitress import serve
from flask_api import status
app = Flask(__name__)
server = 'bla'
database = 'bla'
username = 'bla'
password = 'bla'
driver = '{ODBC Driver 18 for SQL Server}'
connection_string = 'DRIVER='+driver+';SERVER=tcp:'+server + \
';PORT=bla;DATABASE='+database+';UID='+username+';PWD=' + password
def hello(data):
try:
if data["url"] == "":
return jsonify({"message": "Error Code : 404 - Not found"}), status.HTTP_404_NOT_FOUND
Headers = {"Content-Type": "application/json",
"Authorization": "Bearer " + access_token}
resp = requests.post(
data["url"], json=bla, headers=Headers)
if resp.status_code == 200:
values = resp.json()["value"]
{perform some operation here}
return filtered_values, status.HTTP_200_OK
else:
return resp.json()["error"]["message"],resp.status_code
except Exception as e:
print("Error", e)
raise
@app.route("/")
def status():
return jsonify({"status": "OK"}), status.HTTP_200_OK
@app.errorhandler(404)
def not_found(e):
return jsonify({"message": str(e)}), status.HTTP_404_NOT_FOUND
@app.route("/somepath", methods=["GET", "POST"])
def details():
if request.method == "POST":
try:
operation_data = request.get_json()
data, code = hello(operation_data )
if code != 200:
return jsonify({"message": str(data)}), code
else:
if len(data) != 0 and data is not None:
conn = pyodbc.connect(connection_string)
cursor = conn.cursor()
for d in data:
cursor.execute(some query)
conn.commit()
cursor.close()
conn.close()
new_resp = jsonify({"message": "successful"})
return new_resp, status.HTTP_200_OK
else:
new_resp = jsonify({"message": "nothing to do"})
return new_resp, status.HTTP_200_OK
except Exception as exception:
print(exception)
return jsonify(str(exception)), status.HTTP_500_INTERNAL_SERVER_ERROR
else:
return jsonify({"status": str(request.method) + " - Method not allowed"}),status.HTTP_405_METHOD_NOT_ALLOWED
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8000, debug=True)
# serve(app, listen='*:8000')```