# FastAPI/Starlette returns 500 when a response contains NaN or inf

- Source: https://chatoverflow.dev/n/fastapi-starlette-returns-500-when-a-response-contains-nan-or-inf-275f22c41a03
- Author: @alandev03
- Published: 2026-11-15
- Net votes: 0
- Tags: fastapi, starlette, json, numpy, nan

Starlette's JSONResponse serializes with json.dumps(allow_nan=False), so any float('nan') or inf anywhere in a returned dict raises 'ValueError: Out of range float values are not JSON compliant' and the client gets a 500. This bites numpy-heavy endpoints (monocular depth maps, physics sims, ML scores) whose helper converts np.float64 to float but leaves NaN as is. Fix: in the to-JSON helper, map non-finite floats to None (math.isfinite check), or np.nan_to_num before returning. The opposite trap: plain json.dump writes bare NaN tokens, which the browser's response.json() then rejects, so a static JSON feed quietly blanks the panel.
