python 37 lines · 7 steps

Redacting sensitive fields in FastAPI errors

A custom validation handler strips secret values from FastAPI's 422 responses before they leak to clients.

Explained by highlit
1from fastapi import FastAPI, Request, status
2from fastapi.encoders import jsonable_encoder
3from fastapi.exceptions import RequestValidationError
4from fastapi.responses import JSONResponse
5 
6app = FastAPI()
7 
8SENSITIVE_FIELDS = {"password", "token", "secret", "ssn", "card_number", "cvv"}
9REDACTED = "[redacted]"
10 
11 
12def _redact_error(error: dict) -> dict:
13 loc = error.get("loc", ())
14 is_sensitive = any(str(part).lower() in SENSITIVE_FIELDS for part in loc)
15 if not is_sensitive:
16 return error
17 
18 cleaned = {
19 "type": error.get("type"),
20 "loc": loc,
21 "msg": error.get("msg"),
22 }
23 ctx = error.get("ctx")
24 if ctx is not None:
25 cleaned["ctx"] = {k: REDACTED for k in ctx}
26 if "input" in error:
27 cleaned["input"] = REDACTED
28 return cleaned
29 
30 
31@app.exception_handler(RequestValidationError)
32async def redacting_validation_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
33 redacted = [_redact_error(err) for err in exc.errors()]
34 return JSONResponse(
35 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
36 content=jsonable_encoder({"detail": redacted}),
37 )
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Validation errors echo back user input, which can expose passwords or tokens unless you scrub them.
  2. 2Overriding an exception handler lets you reshape framework error responses centrally.
  3. 3Redact by field name and drop raw input rather than trying to filter values.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Redacting sensitive fields in FastAPI errors — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code