Thursday, 29 August 2019

Return 400 error as response in a flask api

I have created a simple flask app that and I'm reading the response from python as:

response = requests.post(url,data=json.dumps(data), headers=headers ) 
data = json.loads(response.text)

Now my issue is that under certain conditions I want to return a 400 or 500 message response. So far I'm doing it like this:

abort(400, 'Record not found') 
#or 
abort(500, 'Some error...') 

This does print the messa on the terminal:

enter image description here

But in the API response I keept getting a 500 error response:

enter image description here

EDIT:

The structure of the code is as follows:

|--my_app
   |--server.py
   |--main.py
   |--swagger.yml

Where server.py has this code:

from flask import render_template
import connexion
# Create the application instance
app = connexion.App(__name__, specification_dir="./")
# read the swagger.yml file to configure the endpoints
app.add_api("swagger.yml")
# Create a URL route in our application for "/"
@app.route("/")
def home():
    """
    This function just responds to the browser URL
    localhost:5000/

    :return:        the rendered template "home.html"
    """
    return render_template("home.html")
if __name__ == "__main__":
    app.run(host="0.0.0.0", port="33")

And main.py has all the function I'm using for the API endpoints.

E.G:

def my_funct():
   abort(400, 'Record not found') 

When my_funct is called, I get the 'Record not found' printed on the terminal, but not in the response from the API itself, where I always get the 500 message error.



from Return 400 error as response in a flask api

No comments:

Post a Comment