In this tutorial, you’ll learn how to handle 404 error in Python Flask. While trying to access a non existing route, you will encounter a not found error. You can handle non existing route error or 404 error gracefully. You can either use render_template with error message to show a customized error message or return a 404 JSON error response. Let’s have a look at the code implementation.

Assuming you have a basic understanding of Flask web application framework. Let’s start by creating a file called app.py and add the following Python code :

from flask import Flask, abort
app = Flask(__name__)

@app.route("/")
def hello():
    return "Welcome to Python Flask."

Save the above changes and run the app using the following terminal command :

# command to run flask app
FLASK_APP=hello.py flask run

Point your browser to http://localhost:5000 and you will the app running. Now if you try to access a non existing route you’ll encounter a 404 not found error. For example : http://localhost:5000/abc.

Handling 404 Error In Flask

To handle 404 Error or invalid route error in Flask is to define a error handler for handling the 404 error.

@app.errorhandler(404) 
def invalid_route(e): 
    return "Invalid route."

Now if you save the changes and try to access a non existing route, it will return “Invalid route” message.

You can either use render_template method to show a custom error page or return a JSON error response.

from flask import Flask, abort
from flask import jsonify
app = Flask(__name__)

@app.errorhandler(404) 
def invalid_route(e): 
    return jsonify({'errorCode' : 404, 'message' : 'Route not found'})

Hope the above code helps. Happy Python coding :)