Start learning free

LESSON 27 OF 188 · BACKEND: YOUR FIRST API

JSON for Unknown Paths in Python

Practice

Your routes send errors as JSON. But when a path has no route at all, like /contact, none of your code runs: Flask answers by itself, with a 404 page in HTML. A browser can show it, but a program that expects JSON can't read it.

Flask lets you replace that page with an error handler: a function decorated with @app.errorhandler and a status number. When Flask is about to send that status itself, it calls the function with the error it caught and sends what the function returns. Here is a handler for another status, 500 (not part of this lesson):

@app.errorhandler(500)
def server_error(error):
    return jsonify({"error": "Something went wrong"}), 500

A handler only runs for the errors Flask makes itself. A route that returns its own 404, like get_product, keeps its own message, and a 405 still gets Flask's page, because your handler is for 404 only. The requests and answers your code must give, in this order:

GET /contact  →  404  {"error": "Not found"}
GET /products/abc  →  404  {"error": "Not found"}
POST /orders  {"product_id": 1, "quantity": 2}  →  404  {"error": "Not found"}
GET /products/9  →  404  {"error": "Product not found"}
DELETE /products  →  405  (Flask's HTML page, as before)
GET /about  →  200  {"name": "Corner Shop", "currency": "USD"}

Your task: add a 404 error handler, not_found(error), that answers {"error": "Not found"} with status 404 through your error_response helper.


Assignment
Follow the Coding Tutorial to add a 404 error handler that answers in JSON.


Hint
The number in @app.errorhandler(404) has no quotes: it's a status, not a path. The function must take one parameter, error, because Flask passes it the error it caught.


STEP 1 OF 3
    Ctrl + Enter to check

    Shop Json 404 in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free