Coverage for faststream/_internal/fastapi/router.py: 93%
107 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
1import json
2import warnings
3from abc import abstractmethod
4from collections.abc import (
5 AsyncGenerator,
6 Awaitable,
7 Callable,
8 Iterable,
9 Mapping,
10 Sequence,
11)
12from contextlib import asynccontextmanager
13from enum import Enum
14from typing import (
15 TYPE_CHECKING,
16 Any,
17 Generic,
18 Optional,
19 Union,
20 cast,
21 overload,
22)
24from fastapi.datastructures import Default
25from fastapi.responses import HTMLResponse
26from fastapi.routing import APIRoute, APIRouter
27from fastapi.utils import generate_unique_id
28from starlette.requests import Request
29from starlette.responses import JSONResponse, Response
30from starlette.routing import BaseRoute, _DefaultLifespan # ruff: ignore[import-private-name]
31from typing_extensions import override
33from faststream._internal.application import StartAbleApplication
34from faststream._internal.broker import BrokerRouter
35from faststream._internal.context import ContextRepo
36from faststream._internal.di.config import FastDependsConfig
37from faststream._internal.types import (
38 MsgType,
39 P_HandlerParams,
40 T_HandlerReturn,
41)
42from faststream._internal.utils.functions import to_async
43from faststream.asgi.factories.asyncapi.try_it_out import TryItOutProcessor
44from faststream.middlewares import BaseMiddleware
45from faststream.specification.asyncapi.site import get_asyncapi_html
47from .config import FastAPIConfig
48from .get_dependant import get_fastapi_dependant
49from .route import wrap_callable_to_fastapi_compatible
51if TYPE_CHECKING:
52 from types import TracebackType
54 from fastapi import FastAPI, params
55 from fastapi.background import BackgroundTasks
56 from fastapi.types import IncEx
57 from starlette import routing
58 from starlette.types import ASGIApp, AppType, Lifespan
60 from faststream._internal.broker import BrokerUsecase
61 from faststream._internal.endpoint.call_wrapper import HandlerCallWrapper
62 from faststream._internal.endpoint.publisher import PublisherUsecase
63 from faststream._internal.proto import NameRequired
64 from faststream._internal.types import BrokerMiddleware
65 from faststream.message import StreamMessage
66 from faststream.specification.base import SpecificationFactory
67 from faststream.specification.schema import Tag, TagDict
70class _BackgroundMiddleware(BaseMiddleware):
71 __slots__ = ()
73 async def __aexit__(
74 self,
75 exc_type: type[BaseException] | None = None,
76 exc_val: BaseException | None = None,
77 exc_tb: Optional["TracebackType"] = None,
78 ) -> bool | None:
79 if not exc_type and (
80 background := cast(
81 "BackgroundTasks | None",
82 getattr(self.context.get_local("message"), "background", None),
83 )
84 ):
85 await background()
87 return await super().after_processed(exc_type, exc_val, exc_tb)
90class StreamRouter(APIRouter, StartAbleApplication, Generic[MsgType]):
91 """A class to route streams."""
93 broker_class: type["BrokerUsecase[MsgType, Any, Any]"]
94 broker: "BrokerUsecase[MsgType, Any, Any]"
95 docs_router: APIRouter | None
96 _after_startup_hooks: list[Callable[[Any], Awaitable[Mapping[str, Any] | None]]]
97 _on_shutdown_hooks: list[Callable[[Any], Awaitable[None]]]
99 title: str
100 description: str
101 version: str
102 license: dict[str, Any] | None
103 contact: dict[str, Any] | None
105 def __init__(
106 self,
107 *connection_args: Any,
108 context: ContextRepo | None,
109 middlewares: Sequence["BrokerMiddleware[MsgType]"] = (),
110 prefix: str = "",
111 tags: list[str | Enum] | None = None,
112 dependencies: Sequence["params.Depends"] | None = None,
113 default_response_class: type["Response"] = Default(JSONResponse),
114 responses: dict[int | str, dict[str, Any]] | None = None,
115 callbacks: list["routing.BaseRoute"] | None = None,
116 routes: list["routing.BaseRoute"] | None = None,
117 redirect_slashes: bool = True,
118 default: Optional["ASGIApp"] = None,
119 dependency_overrides_provider: Any | None = None,
120 route_class: type["APIRoute"] = APIRoute,
121 on_startup: Sequence[Callable[[], Any]] | None = None,
122 on_shutdown: Sequence[Callable[[], Any]] | None = None,
123 deprecated: bool | None = None,
124 include_in_schema: bool = True,
125 setup_state: bool = True,
126 lifespan: Optional["Lifespan[Any]"] = None,
127 generate_unique_id_function: Callable[["APIRoute"], str] = Default(
128 generate_unique_id,
129 ),
130 # Specification information
131 specification: Optional["SpecificationFactory"] = None,
132 specification_tags: Iterable[Union["Tag", "TagDict"]] = (),
133 schema_url: str | None = "/asyncapi",
134 **connection_kwars: Any,
135 ) -> None:
136 broker = self.broker_class(
137 *connection_args,
138 middlewares=(
139 *middlewares,
140 # allow to catch background exceptions in user middlewares
141 _BackgroundMiddleware,
142 ),
143 tags=specification_tags,
144 apply_types=False,
145 **connection_kwars,
146 )
148 self._init_setupable_(
149 broker,
150 config=FastDependsConfig(
151 get_dependent=get_fastapi_dependant,
152 context=context or ContextRepo(),
153 ),
154 specification=specification,
155 )
157 self.setup_state = setup_state
159 super().__init__(
160 prefix=prefix,
161 tags=tags,
162 dependencies=dependencies,
163 default_response_class=default_response_class,
164 responses=responses,
165 callbacks=callbacks,
166 routes=routes,
167 redirect_slashes=redirect_slashes,
168 default=default,
169 dependency_overrides_provider=dependency_overrides_provider,
170 route_class=route_class,
171 deprecated=deprecated,
172 include_in_schema=include_in_schema,
173 generate_unique_id_function=generate_unique_id_function,
174 lifespan=self._wrap_lifespan(lifespan),
175 on_startup=on_startup,
176 on_shutdown=on_shutdown,
177 )
179 self.fastapi_config = FastAPIConfig(
180 dependency_overrides_provider=dependency_overrides_provider,
181 )
183 if self.include_in_schema:
184 self.docs_router = self._asyncapi_router(schema_url)
185 else:
186 self.docs_router = None
188 self._after_startup_hooks = []
189 self._on_shutdown_hooks = []
191 self._lifespan_started = False
193 @property
194 @override
195 def context(self) -> ContextRepo:
196 return self.broker.context
198 def _subscriber_compatibility_wrapper(
199 self,
200 dependencies: Iterable["params.Depends"] = (),
201 response_model: Any = Default(None),
202 response_model_include: Optional["IncEx"] = None,
203 response_model_exclude: Optional["IncEx"] = None,
204 response_model_by_alias: bool = True,
205 response_model_exclude_unset: bool = False,
206 response_model_exclude_defaults: bool = False,
207 response_model_exclude_none: bool = False,
208 ) -> Callable[
209 [Callable[..., Any]],
210 Callable[["StreamMessage[Any]"], Awaitable[Any]],
211 ]:
212 """Decorator before `broker.subscriber`, that wraps function to FastAPI-compatible one."""
214 def wrapper(
215 endpoint: Callable[..., Any],
216 ) -> Callable[["StreamMessage[Any]"], Awaitable[Any]]:
217 """Patch user function to make it FastAPI-compatible."""
218 return wrap_callable_to_fastapi_compatible(
219 user_callable=endpoint,
220 dependencies=dependencies,
221 response_model=response_model,
222 response_model_include=response_model_include,
223 response_model_exclude=response_model_exclude,
224 response_model_by_alias=response_model_by_alias,
225 response_model_exclude_unset=response_model_exclude_unset,
226 response_model_exclude_defaults=response_model_exclude_defaults,
227 response_model_exclude_none=response_model_exclude_none,
228 context=self.context,
229 fastapi_config=self.fastapi_config,
230 )
232 return wrapper
234 def subscriber(
235 self,
236 *extra: Union["NameRequired", str],
237 dependencies: Iterable["params.Depends"],
238 response_model: Any,
239 response_model_include: Optional["IncEx"],
240 response_model_exclude: Optional["IncEx"],
241 response_model_by_alias: bool,
242 response_model_exclude_unset: bool,
243 response_model_exclude_defaults: bool,
244 response_model_exclude_none: bool,
245 **broker_kwargs: Any,
246 ) -> Callable[
247 [Callable[P_HandlerParams, T_HandlerReturn]],
248 "HandlerCallWrapper[P_HandlerParams, T_HandlerReturn]",
249 ]:
250 """A function decorator for subscribing to a message queue."""
251 dependencies = (*self.dependencies, *dependencies)
253 sub = self.broker.subscriber( # type: ignore[call-arg]
254 *extra, # type: ignore[arg-type]
255 dependencies=dependencies,
256 **broker_kwargs,
257 )
259 sub._call_decorators = (
260 self._subscriber_compatibility_wrapper(
261 dependencies=dependencies,
262 response_model=response_model,
263 response_model_include=response_model_include,
264 response_model_exclude=response_model_exclude,
265 response_model_by_alias=response_model_by_alias,
266 response_model_exclude_unset=response_model_exclude_unset,
267 response_model_exclude_defaults=response_model_exclude_defaults,
268 response_model_exclude_none=response_model_exclude_none,
269 ),
270 *sub._call_decorators,
271 )
273 return sub
275 def _wrap_lifespan(
276 self,
277 lifespan: Optional["Lifespan[Any]"] = None,
278 ) -> "Lifespan[Any]":
279 lifespan_context = lifespan if lifespan is not None else _DefaultLifespan(self)
281 @asynccontextmanager
282 async def start_broker_lifespan(
283 app: "FastAPI",
284 ) -> AsyncGenerator[Mapping[str, Any] | None, None]:
285 """Starts the lifespan of a broker."""
286 self.fastapi_config.set_application(app)
288 if self.docs_router:
289 self.schema.title = app.title
290 self.schema.description = app.description
291 self.schema.version = app.version
292 self.schema.contact = app.contact
293 self.schema.license = app.license_info
294 app.include_router(self.docs_router)
296 async with lifespan_context(app) as maybe_context:
297 lifespan_extra = {"broker": self.broker, **(maybe_context or {})}
299 if not self._lifespan_started: 299 ↛ 303line 299 didn't jump to line 303 because the condition on line 299 was always true
300 await self._start_broker()
301 self._lifespan_started = True
302 else:
303 warnings.warn(
304 "Specifying 'lifespan_context' manually is no longer necessary with FastAPI >= 0.112.2.",
305 category=RuntimeWarning,
306 stacklevel=2,
307 )
309 for h in self._after_startup_hooks:
310 lifespan_extra.update(await h(app) or {})
312 try:
313 if self.setup_state: 313 ↛ 317line 313 didn't jump to line 317 because the condition on line 313 was always true
314 yield lifespan_extra
315 else:
316 # NOTE: old asgi compatibility
317 yield None
319 for h in self._on_shutdown_hooks:
320 await h(app)
322 finally:
323 await self.broker.stop()
325 return start_broker_lifespan # type: ignore[return-value]
327 @overload
328 def after_startup(
329 self,
330 func: Callable[["AppType"], Mapping[str, Any]],
331 ) -> Callable[["AppType"], Mapping[str, Any]]: ...
333 @overload
334 def after_startup(
335 self,
336 func: Callable[["AppType"], Awaitable[Mapping[str, Any]]],
337 ) -> Callable[["AppType"], Awaitable[Mapping[str, Any]]]: ...
339 @overload
340 def after_startup(
341 self,
342 func: Callable[["AppType"], None],
343 ) -> Callable[["AppType"], None]: ...
345 @overload
346 def after_startup(
347 self,
348 func: Callable[["AppType"], Awaitable[None]],
349 ) -> Callable[["AppType"], Awaitable[None]]: ...
351 def after_startup(
352 self,
353 func: Callable[["AppType"], Mapping[str, Any]]
354 | Callable[["AppType"], Awaitable[Mapping[str, Any]]]
355 | Callable[["AppType"], None]
356 | Callable[["AppType"], Awaitable[None]],
357 ) -> (
358 Callable[["AppType"], Mapping[str, Any]]
359 | Callable[["AppType"], Awaitable[Mapping[str, Any]]]
360 | Callable[["AppType"], None]
361 | Callable[["AppType"], Awaitable[None]]
362 ):
363 """Register a function to be executed after startup."""
364 self._after_startup_hooks.append(to_async(func))
365 return func
367 @overload
368 def on_broker_shutdown(
369 self,
370 func: Callable[["AppType"], None],
371 ) -> Callable[["AppType"], None]: ...
373 @overload
374 def on_broker_shutdown(
375 self,
376 func: Callable[["AppType"], Awaitable[None]],
377 ) -> Callable[["AppType"], Awaitable[None]]: ...
379 def on_broker_shutdown(
380 self,
381 func: Callable[["AppType"], None] | Callable[["AppType"], Awaitable[None]],
382 ) -> Callable[["AppType"], None] | Callable[["AppType"], Awaitable[None]]:
383 """Register a function to be executed before broker stop."""
384 self._on_shutdown_hooks.append(to_async(func))
385 return func
387 @abstractmethod
388 def publisher(self) -> "PublisherUsecase":
389 """Create Publisher object."""
390 raise NotImplementedError
392 def _asyncapi_router(self, schema_url: str | None) -> APIRouter | None:
393 """Creates an API router for serving AsyncAPI documentation."""
394 if not self.include_in_schema or not schema_url:
395 return None
397 def download_app_json_schema() -> Response:
398 return Response(
399 # `json_dumps` may be orjson, which takes no `indent`:
400 # the downloaded schema stays readable
401 content=json.dumps( # ruff: ignore[banned-api]
402 self.schema.to_specification().to_jsonable(),
403 indent=2,
404 ),
405 headers={"Content-Type": "application/json"},
406 )
408 def download_app_yaml_schema() -> Response:
409 return Response(
410 content=self.schema.to_specification().to_yaml(),
411 headers={
412 "Content-Type": "application/octet-stream",
413 },
414 )
416 def serve_asyncapi_schema(
417 sidebar: bool = True,
418 info: bool = True,
419 servers: bool = True,
420 operations: bool = True,
421 messages: bool = True,
422 schemas: bool = True,
423 errors: bool = True,
424 expandMessageExamples: bool = True,
425 ) -> HTMLResponse:
426 """Serve the AsyncAPI schema as an HTML response."""
427 return HTMLResponse(
428 content=get_asyncapi_html(
429 self.schema.to_specification(),
430 sidebar=sidebar,
431 info=info,
432 servers=servers,
433 operations=operations,
434 messages=messages,
435 schemas=schemas,
436 errors=errors,
437 expand_message_examples=expandMessageExamples,
438 try_it_out_path=f"{schema_url}/try",
439 ),
440 )
442 docs_router = APIRouter(
443 prefix=self.prefix,
444 tags=["asyncapi"],
445 redirect_slashes=self.redirect_slashes,
446 default=self.default,
447 deprecated=self.deprecated,
448 )
449 docs_router.get(schema_url)(serve_asyncapi_schema)
450 docs_router.get(f"{schema_url}.json")(download_app_json_schema)
451 docs_router.get(f"{schema_url}.yaml")(download_app_yaml_schema)
453 # The AsyncAPI docs page renders an interactive "try it out" plugin
454 # that POSTs to ``{schema_url}/try``. Register that endpoint so the
455 # FastAPI plugin can publish messages to the broker, mirroring the
456 # standalone AsgiFastStream behaviour (see issue #2869).
457 try:
458 try_processor = TryItOutProcessor(self.broker)
459 except ValueError:
460 # Broker has no associated TestBroker (e.g. a custom broker):
461 # serve the docs without the interactive "try it out" endpoint.
462 try_processor = None
464 if try_processor is not None: 464 ↛ 484line 464 didn't jump to line 484 because the condition on line 464 was always true
466 async def try_asyncapi_schema(request: Request) -> Response:
467 """Publish a message coming from the AsyncAPI try-it-out plugin."""
468 try:
469 body = await request.json()
470 except Exception as e:
471 return JSONResponse({"details": f"Invalid JSON: {e}"}, 400)
473 result = await try_processor.process(body)
474 return Response(
475 content=result.body,
476 status_code=result.status_code,
477 media_type="application/json",
478 )
480 docs_router.post(f"{schema_url}/try", include_in_schema=False)(
481 try_asyncapi_schema,
482 )
484 return docs_router
486 def include_router( # type: ignore[override]
487 self,
488 router: Union["StreamRouter[MsgType]", "BrokerRouter[MsgType, Any]"],
489 *,
490 prefix: str = "",
491 tags: list[str | Enum] | None = None,
492 dependencies: Sequence["params.Depends"] | None = None,
493 default_response_class: type[Response] = Default(JSONResponse),
494 responses: dict[int | str, dict[str, Any]] | None = None,
495 callbacks: list["BaseRoute"] | None = None,
496 deprecated: bool | None = None,
497 include_in_schema: bool = True,
498 generate_unique_id_function: Callable[["APIRoute"], str] = Default(
499 generate_unique_id,
500 ),
501 ) -> None:
502 """Includes a router in the API."""
503 if isinstance(router, BrokerRouter):
504 for sub in router.subscribers:
505 sub._call_decorators = (
506 self._subscriber_compatibility_wrapper(),
507 *sub._call_decorators,
508 )
510 self.broker.include_router(router)
511 return
513 msg = (
514 "Including a StreamRouter into another StreamRouter is not supported "
515 "and may cause subtle context issues (e.g. message dependencies "
516 "returning EmptyPlaceholder). "
517 "Use a regular broker router (e.g. KafkaRouter, RabbitRouter, etc.) "
518 "for grouping subscribers and include that into the StreamRouter instead. "
519 "See: https://faststream.ag2.ai/latest/getting-started/integrations/fastapi/#multiple-routers"
520 )
521 raise TypeError(msg)