Skip to content

Fix WebSocket close reason to send valid JSON string - #1

Open
veeceey wants to merge 14 commits into
masterfrom
fix-websocket-close-reason-json
Open

Fix WebSocket close reason to send valid JSON string#1
veeceey wants to merge 14 commits into
masterfrom
fix-websocket-close-reason-json

Conversation

@veeceey

@veeceey veeceey commented Feb 10, 2026

Copy link
Copy Markdown
Owner

Summary

This PR fixes a bug in the default websocket_request_validation_exception_handler and is intended for upstream fastapi/fastapi.

  • Bug: The handler passes a Python list (from jsonable_encoder(exc.errors())) as the reason parameter to websocket.close(), which expects a str. The close reason is sent as Python repr with single quotes and None instead of null, making it unparseable as JSON by WebSocket clients.
  • Fix: Wrap with json.dumps() so the close reason is a valid JSON string.
  • Test: Added a regression test that fails on master and passes with the fix.

Before (on master)

[{'loc': ['header', 'x-token'], 'msg': 'Field required', 'type': 'missing', 'input': None}]

After (this PR)

[{"loc": ["header", "x-token"], "msg": "Field required", "type": "missing", "input": null}]

Test plan

  • New test test_websocket_validation_close_reason_is_valid_json - fails on master, passes with fix
  • All existing websocket tests pass
  • All exception handler tests pass
  • All validation error context tests pass

tiangolo and others added 14 commits February 8, 2026 10:18
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Motov Yurii <109919500+YuriiMotov@users.noreply.github.com>
Co-authored-by: Yurii Motov <yurii.motov.monte@gmail.com>
…pi#14873)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
The default `websocket_request_validation_exception_handler` was passing
a Python list (from `jsonable_encoder`) as the `reason` parameter to
`websocket.close()`, which expects a string. This caused the close reason
to be sent as a Python repr (with single quotes and `None` instead of
`null`), making it impossible for clients to parse as JSON.

Wrap the result with `json.dumps()` so that the close reason is a proper
JSON string that clients can reliably deserialize.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@veeceey veeceey changed the title 🐛 Fix WebSocket close reason to send valid JSON string Fix WebSocket close reason to send valid JSON string Feb 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants