Skip to main content

serialize_response

Validates and serializes response content against a provided model field, handling both synchronous and asynchronous validation. If no field is provided, it falls back to encoding the content using jsonable_encoder.

def serialize_response(
field: ModelField | None = None,
response_content: Any,
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

Validates and serializes the response content against a model field, ensuring the data conforms to the expected schema before returning it to the client.

Parameters

NameTypeDescription
field`ModelFieldNone` = None
response_contentAnyThe raw data returned by the endpoint handler that needs to be serialized.
include`IncExNone` = None
exclude`IncExNone` = None
by_aliasbool = TrueWhether to use the field's alias name as defined in the model during serialization.
exclude_unsetbool = FalseWhether to exclude fields that were not explicitly set in the model instance.
exclude_defaultsbool = FalseWhether to exclude fields that have their default values.
exclude_nonebool = FalseWhether to exclude fields that have a value of None.
is_coroutinebool = TrueIndicates if the validation should be performed directly or offloaded to a threadpool for synchronous fields.
endpoint_ctx`EndpointContextNone` = None
dump_jsonbool = FalseIf True, the output will be serialized directly into a JSON string instead of a Python dictionary.

Returns

TypeDescription
AnyThe serialized response data, either as a JSON-compatible dictionary or a JSON string depending on the dump_json flag.