Skip to content

Serialize dataclasses & rich types in mk_app responses#7

Merged
thorwhalen merged 1 commit into
masterfrom
fix/jsonable-encoder-dataclass-responses
May 21, 2026
Merged

Serialize dataclasses & rich types in mk_app responses#7
thorwhalen merged 1 commit into
masterfrom
fix/jsonable-encoder-dataclass-responses

Conversation

@thorwhalen
Copy link
Copy Markdown
Member

Summary

qh.mk_app() endpoints returned HTTP 500 when the wrapped function
returned a value the stdlib json encoder can't handle directly — a
@dataclass, a pydantic model, datetime, Enum, set, UUID,
Decimal, etc.:

Error in <func>: Object of type <T> is not JSON serializable

endpoint.py built the success response with JSONResponse(content=output);
Starlette's JSONResponse.render() calls json.dumps with the default
encoder. A TypedDict instance is a plain dict at runtime so it worked — a
dataclass instance is not, so it raised and qh's generic except wrapped it
as a 500.

Fix

Run the output through FastAPI's jsonable_encoder before constructing the
JSONResponse. It recursively converts dataclasses, pydantic models (v1/v2),
datetime, Enum, set, UUID, Decimal, … into JSON-compatible
primitives. Plain dict/list/scalar outputs pass through unchanged, so the
change is non-breaking — it strictly broadens what serializes.

Tests

Three new tests in test_mk_app.py — a dataclass return, a list of
dataclasses (the ef.EfService.search() shape that surfaced this), and
datetime / Enum. Full suite: 139 passed.

Closes #6

endpoint.py built the success response with JSONResponse(content=output),
which serializes via the stdlib json encoder — only dict/list/scalar. A
dataclass (or pydantic model, datetime, Enum, set, UUID, Decimal, …) raised
"Object of type ... is not JSON serializable" and 500'd.

Run output through FastAPI's jsonable_encoder before constructing the
JSONResponse. Plain dict/list/scalar outputs pass through unchanged, so the
change is non-breaking — it strictly broadens what serializes.

Closes #6
@thorwhalen thorwhalen merged commit 3e1bc03 into master May 21, 2026
2 checks passed
@thorwhalen thorwhalen deleted the fix/jsonable-encoder-dataclass-responses branch May 21, 2026 10:20
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.

mk_app endpoints fail to serialize dataclasses and other rich return types

1 participant