When you need to write logs, cache to Redis, or push data into BackgroundTasks, you can’t hand a Pydantic model or a datetime straight to json.dumps() — it raises TypeError. FastAPI’s jsonable_encoder converts all of those types into JSON-compatible dicts, lists, strings, and numbers in a single line, and it’s the same mechanism FastAPI itself uses to build responses. Use it whenever data leaves an endpoint without going through a response_model.

The Problem

Suppose an endpoint returns user info and you want to write the response to a JSON log, or cache it in Redis so you don’t have to query the database next time. The natural approach is to call model_dump() and then json.dumps(), but model_dump() in its default mode still keeps datetime and Decimal as-is. The result: json.dumps() stops immediately with TypeError: Object of type datetime is not JSON serializable — and your whole logging or caching block never runs.

The snippet below reproduces this exact error:

import json
from datetime import datetime
from decimal import Decimal
from pydantic import BaseModel
class UserOut(BaseModel):
id: int
name: str
created_at: datetime
balance: Decimal
user = UserOut(
id=1, name="Linh",
created_at=datetime(2026, 11, 18, 14, 0, 0),
balance=Decimal("150000.50"),
)
json.dumps(user.model_dump())
# TypeError: Object of type datetime is not JSON serializable

The Solution

A single line of jsonable_encoder is all it takes. The function accepts anything — a Pydantic model, datetime, Decimal, Enum, UUID — and returns a structure made only of JSON-safe types. The example below encodes a UserOut model containing the trickiest types:

import json
from fastapi.encoders import jsonable_encoder
data = jsonable_encoder(user)
print(data)
# {'id': 1, 'name': 'Linh',
# 'created_at': '2026-11-18T14:00:00',
# 'balance': '150000.50'}
print(json.dumps(data)) # works, ready to log or cache

The result is a plain dict: datetime becomes an ISO 8601 string, Enum becomes its string value, and Decimal inside a model becomes a string to keep money exact — avoiding float rounding errors. A standalone Decimal outside a model encodes to a float. To format dates your own way, pass custom_encoder as in the second example.

The exclude_unset=True parameter takes only the fields the client actually sent in a PATCH model — handy for logging changes or doing a partial update without overwriting other fields with None:

class PatchUser(BaseModel):
name: str | None = None
balance: Decimal | None = None
patch = PatchUser(name="Linh")
jsonable_encoder(patch, exclude_unset=True)
# {'name': 'Linh'} — balance wasn't sent, so it won't be overwritten
jsonable_encoder(
datetime(2026, 11, 18, 14, 0, 0),
custom_encoder={datetime: lambda v: v.strftime("%d/%m/%Y %H:%M")},
)
# '18/11/2026 14:00'

One important note: don’t call jsonable_encoder inside an endpoint just to return a response — FastAPI already encodes when it applies response_model. This function is for data that goes outside the response: logs, caches, queues, and BackgroundTasks.

Apply It to Your Project

In a real project, jsonable_encoder shows up most in three places: caching a response in Redis with json.dumps(jsonable_encoder(data)) and a TTL of a few minutes; writing request/response logs as JSON for later lookup; and passing encoded data into BackgroundTasks, because a background task that receives a JSON-safe dict won’t trip over a datetime halfway through. Start with your most-cached endpoint — usually one line is all it takes for the error to disappear.

Related Posts

FAQ

How is jsonable_encoder different from model_dump(mode=”json”)?

For a Pydantic model the two give almost identical results. The strength of jsonable_encoder is that it also handles types that aren’t models — datetime, Decimal, Enum, UUID, or a dataclass — so you can use it for anything you want to turn into JSON.

Does Decimal encode to a number or a string?

It depends on where it sits: a standalone Decimal becomes a float, while inside a Pydantic model it becomes a string so no precision is lost. For money, the string is safer; the receiving side converts it back with Decimal(string).

Should I use jsonable_encoder instead of response_model in an endpoint?

No. FastAPI already encodes the response according to response_model; calling it again is just wasted work. Only use jsonable_encoder when data leaves the response — logging, caching, queueing, or passing into BackgroundTasks.

When do I use custom_encoder?

When the default format isn’t what you want — for example, you want dates as dd/mm/yyyy instead of ISO 8601, or UUIDs in uppercase. Pass a dict mapping a data type to a formatting function, and the encoder applies it to every value of that type.

Have you tried this in your own project? If you hit an error or have a shorter way, leave a comment below — I read them all and will fold the good ideas into the post.

References