Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 50 ยท Responses, errors and docs

jsonable_encoder and serialization control

Control how FastAPI turns Python objects into JSON: use jsonable_encoder, aliases, response_model_exclude_unset, serialization options and custom types, with runnable examples.

JSON only knows strings, numbers, booleans, null, lists and objects. Python has far more: datetime, UUID, Decimal, Enum, set, Pydantic models. Every time an endpoint returns one of those, something has to convert it into plain JSON types. In FastAPI that something is serialization, and most of the time it happens invisibly through response_model.

This lesson opens the box. You will use jsonable_encoder yourself (needed when you store data in a JSON-only place), control the shape of the output with aliases and response_model_* switches, and customize how a type is written. It builds on Response models, so skim that first if response_model is new to you.

Why plain json.dumps fails

json.dumps handles only the basic types. Ask it to write a UUID, a datetime or a Decimal and it raises TypeError. FastAPI's helper jsonable_encoder converts any supported object into a structure of only JSON-safe types (dicts, lists, strings, numbers, booleans, None), which you can then pass to json.dumps, a JSON database column, a message queue or a cache.

Python What jsonable_encoder produces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

What you see: the UUID and datetime became strings (datetime in ISO 8601), the enum became its value, the set became a list, and the date an ISO string. A Decimal inside a plain dictionary became a float, while inside the Pydantic model it was written as the string "19.90", because Pydantic's serializer keeps decimals exact. The keyword arguments (include, exclude, exclude_unset, exclude_none, ...) mirror the ones on model_dump().

Because the model path and the plain-dict path can treat a type differently, put values into models when exactness matters (money, identifiers). A bare dict gets the generic encoder.

When you need it yourself

You rarely call jsonable_encoder inside a normal endpoint: FastAPI already does it on whatever you return. You need it when you hand data to something that only accepts JSON types:

  • a JSON/NoSQL document store (MongoDB, a JSON column, a cache or a queue message),
  • the content= of your own JSONResponse,
  • a test that compares an object with a decoded response,
  • the update flow where a stored dict is merged with a validated model, as in Partial updates.
Python
from fastapi.responses import JSONResponse

@app.get("/ticket")
async def ticket():
    return JSONResponse(content=jsonable_encoder(make_ticket()))

Without jsonable_encoder that JSONResponse would crash on the first UUID: a JSONResponse is the "bare" response class and does not convert anything for you.

Aliases: different names on the wire

A Pydantic alias lets the JSON name differ from the Python attribute, for example when a client expects camelCase while your code uses snake_case:

Python
from pydantic import BaseModel, ConfigDict, Field
from pydantic.alias_generators import to_camel

class Profile(BaseModel):
    model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)

    first_name: str
    signup_date: str
  • On input, the client sends firstName (the alias). With populate_by_name=True, first_name is accepted too.
  • On output, FastAPI serializes with aliases by default (response_model_by_alias=True). If you want the Python names instead, set response_model_by_alias=False on the decorator.
Python Aliases and response_model switches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Compare the four GET outputs: the default uses firstName, /snake switches back to Python names, /slim drops everything that was never set (the unset signupDate and bio disappear), and /nonulls removes None values and the excluded field. The two POSTs show input accepting both names.

exclude_unset is great for PATCH-style responses and sparse documents, but it is a behaviour switch, not a security feature. To hide a sensitive field for good, use a separate output model that does not have it, as taught in Response models.

Computed and custom values

Pydantic v2 offers decorators to control individual fields while serializing:

Python
from pydantic import BaseModel, computed_field, field_serializer
from decimal import Decimal

class Invoice(BaseModel):
    net: Decimal
    tax_rate: Decimal = Decimal("0.2")

    @computed_field
    @property
    def gross(self) -> Decimal:
        return self.net * (1 + self.tax_rate)

    @field_serializer("net", "gross")
    def as_money(self, value: Decimal) -> str:
        return f"{value:.2f}"
  • @computed_field adds a value that is calculated, not stored, to the output (and to the OpenAPI schema).
  • @field_serializer decides how one field is written. The return annotation is also what the docs show.
  • @model_serializer rewrites the whole object when per-field control is not enough.

jsonable_encoder also accepts custom_encoder={Type: function}, but it applies to values handled by its generic path (plain dicts, lists, dataclasses). Types inside Pydantic models are written by the model's own serializer, so for models use field_serializer or a custom type with Annotated[..., PlainSerializer(...)].

Python computed_field, field_serializer and custom_encoder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Response objects that bypass serialization

Remember the hierarchy of what happens to a return value:

  1. If you return a Response (including JSONResponse, HTMLResponse, StreamingResponse), FastAPI sends it as it is. No response_model, no jsonable_encoder.
  2. Otherwise FastAPI validates the value against the response_model (if any) and serializes it.
  3. Without a response_model, FastAPI uses the return annotation if there is one, and finally the generic encoder.

A custom response class changes the final text format. ORJSONResponse and UJSONResponse are faster JSON writers (they need orjson or ujson installed), but note that in recent FastAPI versions, declaring a return type or response_model already makes serialization fast through Pydantic's Rust core, so you rarely need them for speed. The performance lesson discusses this.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does jsonable_encoder(obj) return?

    It converts values like UUID, datetime and Enum into JSON-safe types but leaves you with Python objects, ready for json.dumps or a JSON-only store.
  2. 2. A client sends {"firstName": "Ada"}. The model uses alias_generator=to_camel. What happens on output by default?

    FastAPI serializes by alias by default. Turn it off with response_model_by_alias=False.
  3. 3. When is it appropriate to call jsonable_encoder yourself?

    FastAPI already encodes normal return values. A manual JSONResponse or a document store needs the converted data.
  4. 4. Which Pydantic decorator adds a calculated value to the serialized output?

    @computed_field on a property includes the computed value in the output and in the schema.
  5. 5. You return a JSONResponse from an endpoint that has response_model=Item. What does FastAPI do with the model?

    Returning a Response directly skips validation and serialization, so you are responsible for the content.

Summary

  • jsonable_encoder converts Python values (UUID, datetime, Enum, set, models) into JSON-safe structures; use it for JSON-only stores and hand-built JSONResponse objects.
  • Aliases give the JSON a different spelling from Python; output uses aliases unless response_model_by_alias=False.
  • response_model_exclude_unset, _exclude_none, _exclude_defaults, _include and _exclude shape the output per endpoint, but a dedicated output model is the safe way to hide fields.
  • @computed_field, @field_serializer and @model_serializer customize how fields are written.
  • Returning a Response object bypasses response_model and the encoder entirely.

Next: connect to a document database in MongoDB with Motor.