How to return 400 (Bad Request) on Flask?

Luis Ramon Ramirez Rodriguez picture Luis Ramon Ramirez Rodriguez · Aug 26, 2019 · Viewed 33.9k times · Source

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.

Answer

tituszban picture tituszban · Sep 3, 2019

You have a variety of options:

The most basic:

@app.route('/')
def index():
    return "Record not found", 400

If you want to access the headers, you can grab the response object:

@app.route('/')
def index():
    resp = make_response("Record not found", 400)
    resp.headers['X-Something'] = 'A value'
    return resp

Or you can make it more explicit, and not just return a number, but return a status code object

from flask_api import status

@app.route('/')
def index():
    return "Record not found", status.HTTP_400_BAD_REQUEST

Further reading:

You can read more about the first two here: About Responses (Flask quickstart)
And the third here: Status codes (Flask API Guide)