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
| Name | Type | Description |
|---|---|---|
| field | `ModelField | None` = None |
| response_content | Any | The raw data returned by the endpoint handler that needs to be serialized. |
| include | `IncEx | None` = None |
| exclude | `IncEx | None` = None |
| by_alias | bool = True | Whether to use the field's alias name as defined in the model during serialization. |
| exclude_unset | bool = False | Whether to exclude fields that were not explicitly set in the model instance. |
| exclude_defaults | bool = False | Whether to exclude fields that have their default values. |
| exclude_none | bool = False | Whether to exclude fields that have a value of None. |
| is_coroutine | bool = True | Indicates if the validation should be performed directly or offloaded to a threadpool for synchronous fields. |
| endpoint_ctx | `EndpointContext | None` = None |
| dump_json | bool = False | If True, the output will be serialized directly into a JSON string instead of a Python dictionary. |
Returns
| Type | Description |
|---|---|
Any | The serialized response data, either as a JSON-compatible dictionary or a JSON string depending on the dump_json flag. |