Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/docs/en/getting-started/subscription/msgspec.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,25 @@ To make your message schema reusable between different subscribers and publisher
```python linenums="1" hl_lines="1 15-17 22"
{!> docs_src/getting_started/subscription/mqtt/msgspec_struct.py !}
```

## AsyncAPI schemas

AsyncAPI payload schemas use the serializer configured on the broker, including
`msgspec.Struct`, `msgspec.field` aliases and `msgspec.Meta` constraints. This
requires FastDepends 4.0.0a0 or newer. Both AsyncAPI 2.6 and 3.0 are supported.

The same backend describes subscriber bodies, publisher return annotations and
explicit publisher `schema=` types. A subscriber with one body parameter describes
the whole body; multiple body parameters form an object. Dependency inputs are
included, while injected context and header values are excluded from the body.
Schema generation does not execute handlers or dependencies.

Publisher schemas continue to describe the declared payload type for the generic
broker encoder. Annotation serializers on a return type do not change the generic
publication path. Typed response encoding, raw bytes, custom codecs and batch
publication remain separate transport contracts.

FastStream still uses Pydantic for its internal AsyncAPI document models and the
FastAPI integration. Selecting Msgspec for payloads does not yet remove the
Pydantic installation dependency. A disabled serializer cannot generate typed
payload schemas; no implicit Pydantic payload fallback is used.
60 changes: 23 additions & 37 deletions faststream/_internal/endpoint/publisher/specification.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
from typing import TYPE_CHECKING, Any

from fast_depends.core import build_call_model
from fast_depends.pydantic._compat import create_model, get_config_base # ruff: ignore[import-private-name]
from typing_extensions import TypeVar as TypeVar313

from faststream._internal.configs import BrokerConfig, PublisherSpecificationConfig
from faststream._internal.endpoint.specification import EndpointSpecification
from faststream.specification.asyncapi.message import get_model_schema
from faststream.exceptions import SetupError
from faststream.specification.asyncapi.message import payload_schema
from faststream.specification.asyncapi.utils import to_camelcase

if TYPE_CHECKING:
Expand Down Expand Up @@ -43,48 +43,34 @@ def add_call(self, call: "AnyCallable") -> None:
def get_payloads(self) -> list[tuple[dict[str, Any], str]]:
payloads: list[tuple[dict[str, Any], str]] = []

if self.config.schema_:
body = get_model_schema(
call=create_model(
"",
__config__=get_config_base(),
response__=(self.config.schema_, ...),
),
prefix=f"{self.name}:Message",
)

if body: # pragma: no branch
payloads.append((body, ""))
di_state = self._outer_config.fd_config
factory = di_state._serializer
prefix = f"{self.name}:Message"

if self.config.schema_ is not None:
if factory is None:
msg = "AsyncAPI requires a serializer with JSON Schema support."
raise SetupError(msg)
body = payload_schema(factory, self.config.schema_, prefix=prefix)
payloads.append((body, ""))
else:
di_state = self._outer_config.fd_config

for call in self.calls:
call_model = build_call_model(
call,
dependency_provider=di_state.provider,
serializer_cls=di_state._serializer,
serializer_cls=factory,
)

if call_model.serializer:
response_type = next(
iter(call_model.serializer.response_option.values()),
).field_type
else:
response_type = None

if response_type is not None and response_type is not Parameter.empty:
body = get_model_schema(
create_model(
"",
__config__=get_config_base(),
response__=(response_type, ...),
),
prefix=f"{self.name}:Message",
)

if body:
payloads.append((body, to_camelcase(unwrap(call).__name__)))
serializer = call_model.serializer
if serializer is None:
continue
response_type = serializer.response_option["return"].field_type
if (
factory is not None
and response_type is not None
and response_type is not Parameter.empty
):
body = payload_schema(factory, response_type, prefix=prefix)
payloads.append((body, to_camelcase(unwrap(call).__name__)))

return payloads

Expand Down
11 changes: 5 additions & 6 deletions faststream/_internal/fastapi/get_dependant.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from typing import TYPE_CHECKING, Annotated, Any, cast, get_args, get_origin

from fast_depends.library.serializer import OptionItem
from fast_depends.pydantic import PydanticSerializer
from fast_depends.utils import get_typed_annotation
from fastapi import params
from fastapi.dependencies.models import Dependant
Expand All @@ -12,7 +13,7 @@
get_parameterless_sub_dependant,
get_typed_signature,
)
from pydantic import Field, create_model
from pydantic import Field
from pydantic.fields import FieldInfo

from faststream._internal._compat import PYDANTIC_V2, PydanticUndefined
Expand All @@ -25,9 +26,9 @@
class _FastStreamDependant(Dependant):
"""FastAPI dependant extended with fields required by FastStream."""

__slots__ = ("custom_fields", "flat_params", "model")
__slots__ = ("custom_fields", "flat_params", "serializer_cls")

model: type[Any]
serializer_cls: PydanticSerializer
custom_fields: dict[str, Any]
flat_params: list[OptionItem]

Expand Down Expand Up @@ -145,9 +146,7 @@ def _patch_fastapi_dependent(dependant: "models.Dependant") -> "models.Dependant
f,
)

dependant.model = create_model(
getattr(call, "__name__", type(call).__name__),
)
dependant.serializer_cls = PydanticSerializer(use_fastdepends_errors=False)

dependant.custom_fields = {}
dependant.flat_params = [
Expand Down
Loading
Loading