Validation and Error Handling: 400, 415, 422 and One Error Format
Check every request before using it, answer bad input with the right status code and one consistent JSON error format, and test a matrix of good and bad requests against a real server and with curl.
In this lesson you will
- Validate type, range and presence
- Choose between 400, 415, 413 and 422
- Return one consistent error format
- Test a matrix of bad requests
About 28 minutes
Bad requests are normal requests
Kofi’s API now accepts loans: POST /loans with a tool id, a member name and a number of days. Within a week the server received a loan for minus three days, a tool id that was text, an empty body, and a body that was not JSON at all. None of this was malicious, just the real world: forms are filled in badly, apps have bugs, and bots probe every address. The rule of the back end is that all input is untrusted until it is checked, and checking is part of the design, not an afterthought.
Validation has layers, and each layer has its status code. First the envelope: the Content-Type must be JSON (415 otherwise), the body must not be absurdly large (413), and it must parse as JSON (400, because the request is malformed). Then the content: each field must be present, of the right type and within range. When the JSON is well formed but the values are unacceptable, many APIs answer 422, unprocessable content, with one message for each failing field, so that the front end can show them beside the right inputs. Use one error format for everything, for example {“error”: {“code”: …, “message”: …, “fields”: {…}}}, so that clients need one piece of code to handle every failure, and never leak stack traces or internal details.
| Problem | Status | Example |
|---|---|---|
| Wrong Content-Type | 415 | text/plain body |
| Body too large | 413 | 2 MB payload |
| Not valid JSON | 400 | {“tool_id”: |
| Valid JSON, bad values | 422 | days: -3 |
| Missing credentials | 401 | No token |
| Unexpected server bug | 500 | Hide details |
import threading, json, urllib.request, urllib.error
from http.server import BaseHTTPRequestHandler, HTTPServer
MAX_BODY = 1024
def validate_loan(d):
errors = {}
if not isinstance(d, dict): return {"_": "body must be an object"}
tool = d.get("tool_id")
if not isinstance(tool, int) or isinstance(tool, bool): errors["tool_id"] = "must be an integer"
elif tool < 1: errors["tool_id"] = "must be positive"
name = d.get("member")
if not isinstance(name, str) or not name.strip(): errors["member"] = "is required"
elif len(name) > 40: errors["member"] = "must be at most 40 characters"
days = d.get("days")
if not isinstance(days, int) or isinstance(days, bool): errors["days"] = "must be an integer"
elif not 1 <= days <= 14: errors["days"] = "must be between 1 and 14"
return errors
class H(BaseHTTPRequestHandler):
def reply(self, code, obj):
b = json.dumps(obj).encode()
self.send_response(code); self.send_header("Content-Type", "application/json"); self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
def fail(self, code, kind, msg, fields=None):
self.reply(code, {"error": {"code": kind, "message": msg, "fields": fields or {}}})
def do_POST(self):
if self.headers.get("Content-Type", "").split(";")[0] != "application/json": return self.fail(415, "unsupported_media_type", "send application/json")
n = int(self.headers.get("Content-Length", 0))
if n > MAX_BODY: return self.fail(413, "too_large", "body over %d bytes" % MAX_BODY)
try: data = json.loads(self.rfile.read(n))
except ValueError: return self.fail(400, "bad_json", "body is not valid JSON")
errs = validate_loan(data)
if errs: return self.fail(422, "validation_failed", "some fields are invalid", errs)
self.reply(201, {"loan": data})
def log_message(self, *a): pass
srv = HTTPServer(("127.0.0.1", 0), H); url = "http://127.0.0.1:%d/loans" % srv.server_address[1]
threading.Thread(target=srv.serve_forever, daemon=True).start()
def post(body, ctype="application/json"):
req = urllib.request.Request(url, data=body, method="POST", headers={"Content-Type": ctype})
try: r = urllib.request.urlopen(req)
except urllib.error.HTTPError as e: r = e
return r.status if hasattr(r, "status") else r.code, json.loads(r.read())
cases = [
("good request", json.dumps({"tool_id": 2, "member": "Ama", "days": 5}).encode(), "application/json"),
("negative days", json.dumps({"tool_id": 2, "member": "Ama", "days": -3}).encode(), "application/json"),
("text tool id", json.dumps({"tool_id": "two", "member": "Ama", "days": 3}).encode(), "application/json"),
("many problems", json.dumps({"tool_id": 0, "member": " ", "days": 99}).encode(), "application/json"),
("true as a number", json.dumps({"tool_id": True, "member": "Ama", "days": 3}).encode(), "application/json"),
("not JSON", b'{"tool_id": ', "application/json"),
("wrong type", b"tool_id=2", "text/plain"),
("too large", b'{"member": "' + b"x" * 2000 + b'"}', "application/json"),
("array body", b"[1, 2]", "application/json"),
]
results = {}
for label, body, ct in cases:
code, obj = post(body, ct)
fields = obj.get("error", {}).get("fields", {})
print(label.ljust(17), code, obj["error"]["code"] if "error" in obj else "created", fields if fields else "")
results[label] = [code, fields]
print("DATA " + json.dumps(results))
srv.shutdown()
good request 201 created
negative days 422 validation_failed {'days': 'must be between 1 and 14'}
text tool id 422 validation_failed {'tool_id': 'must be an integer'}
many problems 422 validation_failed {'tool_id': 'must be positive', 'member': 'is required', 'days': 'must be between 1 and 14'}
true as a number 422 validation_failed {'tool_id': 'must be an integer'}
not JSON 400 bad_json
wrong type 415 unsupported_media_type
too large 413 too_large
array body 422 validation_failed {'_': 'body must be an object'}
Nine requests went to the server. The good one was created with 201. The next four were well-formed JSON with wrong values, and each got 422 with an error for the exact field: negative days gave “must be between 1 and 14”, a text tool id gave “must be an integer”, and the request with three problems got all three at once, tool_id “must be positive”, member “is required” and days “must be between 1 and 14”, so a form can show every message on one screen instead of fixing mistakes one by one. A surprise from Python: true is a number there, so the code rejects booleans explicitly, and “true as a number” was refused. A broken JSON body got 400, the wrong Content-Type got 415, and a body of 2,000 bytes against a limit of 1,024 got 413.
Every failure has the same shape, an error object with a code, a message and a fields map, so the front end handles all of them with one function. Equally important is what the responses do not contain: no stack trace, no file names, no SQL. Attackers learn from those details. The detailed error goes to the server’s own log, with a request id, and the client gets a short, safe message. The last case, a JSON array where an object was expected, was also caught by the validator and answered 422 with a message about the body, because the validation function checks the type of the whole body first.
Independent check: curl, with a different tiny server that follows the same envelope rules, got the statuses 201 for a good body, 422 for a body with days -3, 400 for a truncated JSON body and 415 for text/plain, which are the same codes that the Python client saw for the same kinds of mistake. The field messages were also checked against the expected dictionary for four of the cases, written separately in the test.
Check by hand: the validator allows days from 1 to 14, so 5 is accepted, and -3 and 99 are not. The tool id 0 is not positive, and ” “, only spaces, is empty after strip. In the many-problems case that is three errors, one for each field.
Browsers and apps can be bypassed. The back end is the last line of defence and must check every value that comes from outside, including headers, query strings and cookies.
Describe what a valid value looks like, a type, a range and a maximum length, instead of trying to list every bad value. Anything that does not match is refused.
Every program in this lesson was run while the course was written, with Python 3.13 and only its standard library (http.server, sqlite3, hashlib, hmac), with a real server on a free local port, and cross-checked with curl, openssl or a second implementation. Tools and versions change, so check the official documentation for current behaviour. Whether to answer 400 or 422 for invalid values varies between teams. Pick one rule, document it, and apply it consistently.
Practice
Add a maximum of three open loans per member, answered with 409 conflict. Return 404 for a tool id that does not exist in the database. Log the full error with a request id and return only the id to the client.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Which status fits a body that is not valid JSON?
- 422
- 400
- 415
- 404
The request is malformed.
Which status fits valid JSON with a negative number of days?
- 422
- 200
- 500
- 401
Many teams use 400 as well; be consistent.
Why return one error format everywhere?
- Clients need one piece of code
- It is shorter
- Browsers require it
- It hides bugs
Consistency.
Why should error responses not include stack traces?
- They are too long
- They break JSON
- They are slow
- They reveal internals to attackers
Log them privately instead.
Why reject booleans explicitly in Python?
- Booleans are invalid JSON
- JSON has no booleans
- It is faster
- True counts as the number 1 in Python
bool is a subclass of int.
Summary
- All input is untrusted until checked.
- Use 415, 413, 400 and 422 for the layers of a bad request.
- One error format with field-level messages.
- Never leak internals in error responses.
Questions
Should I use a validation library?
For real projects, yes: libraries such as JSON Schema validators or those built into frameworks cover many cases. Learn the manual way first, and check the documentation of the one you pick.
What is 409?
Conflict: the request is valid but clashes with the current state, for example a tool that is already on loan.
How strict should validation be?
Strict about structure and ranges, lenient about harmless formatting, such as extra spaces around a name. Be careful with rules about people's names and addresses, which vary widely.
