Skip to main content

serialize_response

Serializes the response content, optionally validating it against a Pydantic model field. If a field is provided, it validates the content and then serializes it using the field's serializer; otherwise, it encodes the content as JSON.

def serialize_response(
field: ModelField | None = None,
response_content: Any = None,
include: IncEx | None = None,
exclude: IncEx | None = None,
by_alias: bool = True,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
is_coroutine: bool = True,
endpoint_ctx: EndpointContext | None = None,
dump_json: bool = False
) - > Any

Serializes the response content, optionally validating it against a Pydantic model field. This function is used to prepare the response data for output, applying inclusion/exclusion rules and handling potential validation errors.

Parameters

NameTypeDescription
field`ModelFieldNone` = None
response_contentAny = NoneThe raw response content to be serialized.
include`IncExNone` = None
exclude`IncExNone` = None
by_aliasbool = TrueIf True, fields are serialized using their alias names as defined in the Pydantic model. If False, original field names are used.
exclude_unsetbool = FalseIf True, fields that were not explicitly set during model instantiation are excluded from the serialized output.
exclude_defaultsbool = FalseIf True, fields with their default values are excluded from the serialized output.
exclude_nonebool = FalseIf True, fields with a value of None are excluded from the serialized output.
is_coroutinebool = TrueIndicates whether the function is being called from within a coroutine. This affects how validation is performed (directly or via a threadpool).
endpoint_ctx`EndpointContextNone` = None
dump_jsonbool = FalseIf True, the field's serialize_json method is used for serialization; otherwise, the serialize method is used. This determines if the output is a JSON string or a Python object.

Returns

TypeDescription
AnyThe serialized response content, which can be a validated Pydantic model instance or a JSON-encodable object.