JSON APIs and Error Handling

JSON APIs and Error Handling in Flask: A hospital laboratory receives requisitions all day. A ward or a clinic sends a sample and a request to run certain…

The Analogy: The Clinical Laboratory Requisition and Report

A hospital laboratory receives requisitions all day. A ward or a clinic sends a sample and a request to run certain tests, and the lab's entire value rests on one habit: it returns the answer on the same standard report form every single time. The ordering system on the other end is a computer, not a person reading prose, so the form has fixed fields in fixed places, and that predictability is what lets results flow back into a patient's chart without a human retyping anything.

Every report carries the same header fields -- requisition number, test name, the result, and a status marking the result normal or abnormal -- plus a stamp that says at a glance whether the receiving system should act now or file it away. The computer never tries to interpret a paragraph of free text; it reads the status field and the named values. This is exactly a JSON API response: a fixed shape of named fields the client can parse mechanically, carried alongside a status code that summarises the outcome before anything looks inside.

The discipline that separates a good lab from a dangerous one is how it handles a sample it cannot process. A hemolysed, mislabelled, or under-filled sample does not vanish and does not come back as a hand-scribbled note. It comes back on the very same report form, marked rejected, with a specific reason code, so the ordering system can tell a rejection apart from a normal result and knows precisely why. And crucially, the report never carries the lab's internal notes -- which analyser was used, the calibration logs, the technician's grumbling -- that machinery stays behind the counter.

The failure mode is a lab that breaks all of this under pressure. When something goes wrong it returns a blank page, or a free-text sticky note, or, worst of all, photocopies its internal error log straight onto the patient report. Now the ordering system cannot parse the answer, cannot distinguish "sample lost" from "result pending," and either retries blindly or drops the patient on the floor; meanwhile confidential internal detail has leaked to anyone holding the page. That is precisely an API that answers errors with HTML crash pages, bare 500s, or raw stack traces: the client cannot handle the failure programmatically, and your internals spill out. This lesson builds APIs that always answer on the same JSON form, with an honest status code, and that turn every failure into a structured, safe response rather than a crash or a leak.


Syntax or Core Structure

Two primitives cover most of a JSON API. jsonify turns keyword arguments or a dict into a response whose body is JSON and whose Content-Type is application/json, and returning a (body, status) tuple sets the HTTP status code. A view that returns jsonify(...) alone is a 200; return it with a number and you have named the outcome.

from flask import Flask, jsonify

app = Flask(__name__)


@app.get("/report/<int:sample_id>")
def report(sample_id):
    return jsonify(sample=sample_id, status="normal", value=4.2)


@app.get("/missing")
def missing():
    return jsonify(error="not_found", message="no such sample"), 404


client = app.test_client()
r1 = client.get("/report/7")
print(r1.status_code, r1.content_type)
print(r1.get_json())
r2 = client.get("/missing")
print(r2.status_code)
print(r2.get_json())

Output:

200 application/json
{'sample': 7, 'status': 'normal', 'value': 4.2}
404
{'error': 'not_found', 'message': 'no such sample'}

The first response carries the application/json content type without you setting a header, and get_json parses the body straight back into a Python dict, which is what a real client does. The second returns the same clean shape but with a 404, showing the pattern for a handled error: a parseable body plus an honest status code, never an empty response. The key order is stable because Flask's default JSON provider sorts keys alphabetically, so error precedes message and sample precedes status every time -- a small thing that makes responses and their tests deterministic.


Technical Depth: Turning Failures Into Responses

An error in a JSON API is not an exception that escapes to the user; it is a response you chose to send. Flask gives you abort to raise a standard HTTP error, and errorhandler to decide what any error -- an HTTP code or one of your own exception classes -- turns into on the way out. The goal is that every path, success or failure, exits through one of these and produces the same shape of JSON with a truthful status code.

Choosing that status code well is half the job, because the number is the part clients branch on before reading the body.

StatusMeaningTypical use
200OKA successful read or action
201CreatedA POST created a new resource
400Bad RequestMalformed syntax the server cannot parse
401UnauthorizedNo or invalid authentication
403ForbiddenAuthenticated but not allowed
404Not FoundNo such route or resource
422Unprocessable EntityWell-formed but fails validation rules
500Internal Server ErrorAn unexpected bug on the server

abort and a JSON error handler

abort(404) raises the built-in NotFound exception, and by default Flask renders it as an HTML page. Registering @app.errorhandler(404) lets you replace that page with JSON, so an API client gets a parseable body instead of markup it cannot use.

from flask import Flask, jsonify, abort

app = Flask(__name__)


@app.errorhandler(404)
def not_found(e):
    return jsonify(error="not_found", message="resource does not exist"), 404


@app.get("/sample/<int:n>")
def sample(n):
    if n != 1:
        abort(404)
    return jsonify(sample=1, status="normal")


client = app.test_client()
for path in ["/sample/1", "/sample/2"]:
    r = client.get(path)
    print(path, r.status_code, r.get_json())

Output:

/sample/1 200 {'sample': 1, 'status': 'normal'}
/sample/2 404 {'error': 'not_found', 'message': 'resource does not exist'}

The existing sample returns normally; the missing one calls abort(404), which the handler catches and reshapes into the same JSON envelope the rest of the API uses. One handler covers every abort(404) and every unmatched route in the application, so you write the not-found shape once rather than in each view.


Mapping a domain exception to a response

The cleanest pattern for a real API is a single custom exception carrying its own status and code. Views raise it wherever a rule is broken, and one handler renders every instance into JSON. Business logic stops threading status codes through return values and simply throws.

from flask import Flask, jsonify

app = Flask(__name__)


class ApiError(Exception):
    def __init__(self, message, status=400, code="bad_request"):
        super().__init__(message)
        self.message = message
        self.status = status
        self.code = code


@app.errorhandler(ApiError)
def handle_api_error(e):
    return jsonify(error=e.code, message=e.message), e.status


@app.get("/withdraw/<int:amount>")
def withdraw(amount):
    if amount > 100:
        raise ApiError("amount exceeds limit", status=422, code="limit_exceeded")
    return jsonify(ok=True, withdrawn=amount)


client = app.test_client()
for amt in [50, 500]:
    r = client.get(f"/withdraw/{amt}")
    print(r.status_code, r.get_json())

Output:

200 {'ok': True, 'withdrawn': 50}
422 {'error': 'limit_exceeded', 'message': 'amount exceeds limit'}

The allowed withdrawal returns 200; the oversized one raises ApiError with a 422 and a machine-readable limit_exceeded code, which the handler turns into the standard envelope. The view never builds an error response itself -- it states the rule and throws -- and every endpoint that raises ApiError produces an identical shape, so clients can rely on error and message being present on every failure.


Real World Example: A Small Orders API With One Way to Fail

This is a compact resource API that reads and creates orders. It has exactly three error handlers -- one for its own ApiError, one for 404s, and one catch-all for anything unexpected -- so every response, from a normal read to an outright bug, leaves through a JSON envelope. The /boom route deliberately divides by zero to show what happens when an unforeseen exception escapes a view.

from flask import Flask, jsonify, request

app = Flask(__name__)
ORDERS = {1: {"item": "book", "qty": 2}}


class ApiError(Exception):
    def __init__(self, message, status, code):
        super().__init__(message)
        self.message, self.status, self.code = message, status, code


@app.errorhandler(ApiError)
def on_api_error(e):
    return jsonify(error=e.code, message=e.message), e.status


@app.errorhandler(404)
def on_404(e):
    return jsonify(error="not_found", message="no such route or resource"), 404


@app.errorhandler(Exception)
def on_uncaught(e):
    return jsonify(error="internal", message=str(e)), 500


@app.get("/orders/<int:oid>")
def get_order(oid):
    order = ORDERS.get(oid)
    if order is None:
        raise ApiError("order not found", 404, "order_missing")
    return jsonify(id=oid, **order)


@app.post("/orders")
def create_order():
    data = request.get_json(silent=True) or {}
    if "item" not in data:
        raise ApiError("item is required", 422, "validation_error")
    return jsonify(created=True, item=data["item"]), 201


@app.get("/boom")
def boom():
    return 1 / 0


client = app.test_client()

r = client.get("/orders/1")
print(r.status_code, r.get_json())

r = client.get("/orders/99")
print(r.status_code, r.get_json())

r = client.post("/orders", json={"item": "pen"})
print(r.status_code, r.get_json())

r = client.post("/orders", json={})
print(r.status_code, r.get_json())

r = client.get("/boom")
print(r.status_code, r.get_json())

Output:

200 {'id': 1, 'item': 'book', 'qty': 2}
404 {'error': 'order_missing', 'message': 'order not found'}
201 {'created': True, 'item': 'pen'}
422 {'error': 'validation_error', 'message': 'item is required'}
500 {'error': 'internal', 'message': 'division by zero'}

Every line of output is the same shape: an object the client can parse, paired with a status code that means something. The read returns the order, the missing order returns a 404 with a domain code, the valid POST returns 201, the POST without an item returns 422, and the divide-by-zero bug returns 500. Not one of them is an HTML page or a dropped connection, so a client can branch on the status and read error and message uniformly.

The status codes are deliberately distinct because they tell the caller different things. A 404 says the resource is not there, a 422 says the request was understood but broke a rule, and a 500 says the server itself failed. Collapsing these into one code, or returning 200 with an error field buried in the body, forces clients to guess; keeping them separate lets a client retry a 500, fix its input on a 422, and give up on a 404.

Notice that the missing order raises ApiError(..., 404, "order_missing") rather than abort(404). Both end as 404 JSON, but the domain code order_missing is more specific than the routing handler's not_found, which now fires only for genuinely unknown routes. That distinction lets a client tell "you asked for an order that does not exist" apart from "you called a URL that is not part of this API."

The genuine flaw is the catch-all handler: message=str(e) echoes the exception's text straight to the client. Here that text is a harmless "division by zero," but on a real bug the same line would leak a database query, a file path, or a secret that happened to be in the exception's arguments, handing an attacker a map of your internals. Worse, the handler logs nothing, so the 500 is invisible to whoever operates the service -- the bug is served to users and hidden from the team at the same time. The fix is to log the full exception server-side with a correlation id and return only a generic message plus that id to the client, so operators can find the trace while the response stays opaque. A catch-all is essential, but it must hide details outward and reveal them inward, never the reverse.


Common Mistakes

  1. Serving HTML errors to JSON clients. Flask's default 404 and 500 responses are HTML pages. Without JSON error handlers, a client expecting an object gets markup it cannot parse, usually surfacing as a cryptic parse failure far from the real cause.
  1. Echoing exception text to the client. Putting str(e) or a stack trace in the response body leaks file paths, queries, and sometimes secrets. Return a generic message and keep the detail in your server logs.
  1. Returning 200 for failures. Signalling an error only through a field in the body while the status stays 200 forces every client to open and inspect the body. The status code exists precisely so callers can branch before parsing.
  1. Serializing values jsonify cannot handle. A datetime, Decimal, or ORM instance raises a serialization error. Convert to primitives first -- isoformat(), float(), a plain dict -- or configure a provider that knows how.
  1. Hand-building JSON and losing the content type. json.dumps into a returned string sends text/html, so clients may not treat it as JSON. Use jsonify, or set the mimetype explicitly, so the header matches the body.
  1. Not guarding request.get_json(). On a missing or malformed body it raises a 400 or returns None. Call it with silent=True and validate the result yourself instead of letting an opaque 400 escape.
  1. Inconsistent error shapes. One endpoint returns error, another returns detail, a third nests differently. Clients cannot write one handler for all of them. Choose a single envelope and use it everywhere.
  1. Using the wrong status code. A 404 for a validation failure, a 200 for a creation, or a 500 for bad user input all mislead the caller. Match the code to the cause so retries and fixes are automatic.
  1. Catching everything and logging nothing. A catch-all handler that swallows the exception without recording it makes production failures invisible. Always log the real error before returning the safe response.

Best Practices

  • Define one error envelope and reuse it. Decide on a shape -- error for a machine code and message for a human string is a fine minimum -- and return it from every failure path so clients write a single handler.
  • Register JSON handlers for the errors clients will hit. Cover at least 404, 405, and 500, plus your own exception type, so no request can fall through to an HTML page.
  • Model failures as a custom exception. Give it a status and a code, raise it from business logic, and render it in one handler. Views state rules and throw rather than assembling error responses inline.
  • Choose the most specific correct status code. Let the number carry the meaning -- 201 for created, 422 for invalid input, 403 versus 401 for authorization versus authentication -- so clients act without parsing prose.
  • Hide internals outward, reveal them inward. Log the full exception with a correlation id server-side and return only a generic message and that id, so operators can trace a failure the client cannot read.
  • Validate input and answer with 422 and detail. Reject bad requests before they reach your models and return which fields failed and why, so the caller can correct and retry.
  • Serialize explicitly. Give models a to_dict method or use a schema library rather than hoping jsonify guesses right; explicit serialization keeps responses stable as models change.
  • Test the error paths, not just the happy path. Assert the status code and body of your 404, 422, and 500 responses the same way you assert successes, since those are the paths clients depend on most under stress.

Practice Exercises

  1. Register a 405 Method Not Allowed JSON handler. Send a POST to a GET-only route with the test client and confirm you get a 405 and your standard error envelope rather than Flask's HTML page.
  1. Add a DELETE /orders/<int:oid> route that raises ApiError with order_missing and 404 for an unknown id, and returns 200 on success. Test both cases and assert the status code and body of each.
  1. Fix the leaking catch-all. Rewrite the Exception handler so it logs the exception server-side and returns {"error": "internal", "request_id": ...} with no str(e). Trigger the /boom route and assert the response body no longer contains the words "division by zero".
  1. Add validation to POST /orders requiring qty to be a positive integer. Return 422 with a message naming the field when it is missing or not positive, and test a request with no qty and one with a negative qty.